如何在JavaScript中获取GET变量的值?

17

可能是重复问题:
如何在JavaScript中获取查询字符串变量?

我该如何在JavaScript中获取GET变量?

我想将它传递给jQuery函数。

function updateTabs(){

            //var number=$_GET['number']; how can i do this?
        alert(number);
        $( "#tabs" ).tabs({ selected: number });

    }

http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/ - Aurimas Ličkus
3个回答

57
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1) {
    var query = document.location
                   .toString()
                   // get the query string
                   .replace(/^.*?\?/, '')
                   // and remove any existing hash string (thanks, @vrijdenker)
                   .replace(/#.*$/, '')
                   .split('&');

    for(var i=0, l=query.length; i<l; i++) {
       var aux = decodeURIComponent(query[i]).split('=');
       $_GET[aux[0]] = aux[1];
    }
}
//get the 'index' query parameter
alert($_GET['index']);

1
我认为你的代码需要在第9行运行unescape()函数。除此之外,这是一个很好的解决方案。 - Mathias Schwarz
2
最好同时使用decodeURIComponent来处理参数名和参数值。 - Aliaksei Nikuliak
你是不是想说 if (...index('?') !== -1)?这可是很大的区别。 - eatonphil
1
@phileaton,你说得对。我不知道那是怎么发生的,也不知道为什么其他人现在才注意到这个问题。谢谢。 - gion_13
split('&'), => split('&'); - Jens Hendar
显示剩余3条评论

9

写:

var $_GET=[];
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(a,name,value){$_GET[name]=value;});

然后是$_GET['number']

1
在JS中不要创建没有var的变量。我建议避免在JS中以$开头命名变量,这不是典型的做法。不要使用数组来保存键/值对,而应该使用普通对象。 - Quentin
1
@Quentin:在变量前面加上美元符号通常被用作 jQuery 对象的约定。例如 var $rows = $("tr") - Jordan Arsenault
@JordanArseno - 我从未说过这在标准中是不允许的,只是这不是JavaScript的典型用法。 - Quentin

-3

试试这个

if (location.search != "")
{
    var x = location.search.substr(1).split(";")
    for (var i=0; i<x.length; i++)
    {
         var y = x[i].split("=");
         alert("Key '" + y[0] + "' has the content '" + y[1]+"'")
    }
}

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