且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery从URL获取查询字符串

更新时间:2021-09-10 22:53:52

来自:这就是您所需要的:)

以下代码将返回一个包含URL参数的JavaScript对象:

The following code will return a JavaScript Object containing the URL parameters:

// Read a page's GET URL variables and return them as an associative array.
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;
}

例如,如果您具有URL:

For example, if you have the URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

此代码将返回:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

您可以这样做:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];