使用Javascript从URL参数中获取变量

6
我正在尝试使用JavaScript获取URL值,到目前为止我只能获取纯数字,而不能获取混合数字和字母或仅字母的值。我找不到任何可用的函数示例,允许检索包含数字和字母的值,只有数字。我没有使用任何非字母数字字符。我试图传递的一个示例值是“42p316041610751874cm83p2306600132141”。
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}

 var first = getUrlVars()["test"];

任何帮助都将是极好的,谢谢。

很奇怪,你的代码应该可以运行。 - Blender
我尝试了一下,对我有效。我使用的是这个URL: http://localhost/test/index.html?test=42p316041610751874cm83p2306600132141 - Brigand
我正在使用jQuery Mobile作为网站的框架,如果这有关系的话? - cWoolf
类似的问题?https://dev59.com/nHNA5IYBdhLWcg3wmfAa - Timo Huovinen
4个回答

6
以下是两个答案的精简版本:

这里是以上两个答案的简化版本:

function gup (name) {
  name = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)');
  return (window.location.href.match (name) || ['', ''])[1];
}

更易于打字、更易于处理,我认为更易于阅读。可能因人而异。

4

我使用这个函数,效果非常好。我不记得它是从哪里得到的,但是它很棒:

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
} 

如果你有一个像 http://www.exmaple.com/path?p1=lkjsd234&p2=klsjd987 这样的URL,你可以使用:

alert(gup('p1')); // shows 'lkjsd234';

这是我使用的。我第一次看到它是在https://dev59.com/EXNA5IYBdhLWcg3wZ85R#979997。 - Michael Plautz

0

你的代码看起来应该可以工作,如果有帮助的话,我使用下面的函数

 function getParam(name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec (window.location.href);
    if (results == null)
        return "";
        else
        return results[1];  
}

var first = getParam("test");

0

你的方法应该是可行的。这是我的版本,供参考:

var o = {
    keys: [ ],
   values: [ ]
}

/* 
You could just use the window#location#search value to get the query sub-String of the currently loaded URL

 var q = window.location.search.substring(1) ; 

For now we'll use a query String from a Google search for "MDN window location"
*/

q = "q=mdn+window+location&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:de:official&client=firefox-a"

for( var i = 0 , a = q.split("&"), p ; i < a.length ; i++ ) {
    p = a[i] ;
    if(  ( b = p.split("=") )  !=  null ) {
        o.keys[i] = b[0] ;
        o.values[i] = b[1] ;
    }
}


console.log("(!!) o: " + o.toSource( ) ) ;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接