如何使用javascript(Jquery)检索查询字符串参数和值?

时间:2021-08-26 12:06:48

Click me

$('.clickme').click(function(event) {
event.preventDefault();
var stringId = $(this).attr("id");
    var mId = stringId.substring(2)
....

I can retrieve the value of id using ID of anchor element. I think I should be able to get it directly from href. So how do I retrieve value of id and status from HREF (url query string)?

我可以使用anchor元素的ID来检索id的值。我想我应该可以直接从href获取它。那么如何从HREF(url查询字符串)中检索id和status的值?

I am using Jquery.

我正在使用Jquery。

Thank you for your help.

谢谢您的帮助。

UPDATE: Also how do I can get all of the URL value .. i.e. "test.php?id=100&blah=blah"?

更新:另外我如何获得所有的URL值...即“test.php?id = 100&blah = blah”?

6 个解决方案

#1


This code:

function querySt(ji) {
    hu = $(".clickme").attr("href");
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

To use it:

要使用它:

document.write(querySt("id"));
document.write(querySt("status"));

Answer to your 'update':

回答您的“更新”:

http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

#2


var stringId = $(this).attr("id"); // this will return p_100
var stringId = $(this).attr("id").split('_')[1]; // this will return 100

var attr= $(this).attr("href"); // this will return all href attribute value

UPDATE

//href="test.php?id=100&status=pending&time=2009"
var attrFromAnchor= $(this).attr("href").split('?')[1].split('&')[0].split('=')[1]; // returns 100

#3


There are a lot of good solutions here but I figured I'd post my own. Here's a quick little function I threw together which will parse a query string in the format from either window.location.search or from a provided search string value;

这里有很多好的解决方案,但我想我会发布自己的解决方案。这是一个快速的小函数,我将它放在一起,它将从window.location.search或提供的搜索字符串值解析格式的查询字符串;

It returns a hash of id value pairs so you could reference it in the form of:

它返回id值对的散列,因此您可以以下列形式引用它:

var values = getQueryParams();
values['id']
values['blah']

Here's the code:

这是代码:

/*
 This function assumes that the query string provided will
 contain a ? character before the query string itself.
 It will not work if the ? is not present.

 In addition, sites which don't use ? to delimit the start of the query string
 (ie. Google) won't work properly with this script.
 */
function getQueryParams( val ) {
    //Use the window.location.search if we don't have a val.
    var query = val || window.location.search;
    query = query.split('?')[1]
    var pairs = query.split('&');
    var retval = {};
    var check = [];
    for( var i = 0; i < pairs.length; i++ ) {
        check = pairs[i].split('=');
        retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
    }

    return retval;
}

To get the value of the query string from the URL without string parsing you can do:

要从URL中获取查询字符串的值而不进行字符串解析,您可以执行以下操作:

window.location.search.substr(1)

If you want the name of the page before the ? you still need to do a little string parsing:

如果你想要之前的页面名称?你还需要做一个小的字符串解析:

var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me

Hope this helps! Cheers.

希望这可以帮助!干杯。

#4


Here's a concise (yet complete) implementation for getting ALL name/value pairs from a query string:

这是一个简洁(但完整)的实现,用于从查询字符串中获取所有名称/值对:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {};
    var tokens;

    while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

#5


No need for jQuery, this solution works on all browsers:

不需要jQuery,这个解决方案适用于所有浏览器:

function querySt(ji)
{
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
    ft = gy[i].split("=");
    if (ft[0] == ji) {
    return ft[1];
    }
    }
    return "";
}

#6


Answers here are outdated now.

这里的答案现在已经过时了。

See this solution using Vanilla JavaScript (ES5)

var qd = {}; // qd stands for query dict
document.getElementById("p_100")[0].href.split("?")[1].split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,]})

I like to pretend it's oneliner, but I was told it's not. hmm...Who would split chained function calls on new lines anyways, right?

我喜欢假装它是oneliner,但我被告知它不是。嗯......无论如何,谁会在新线上拆分链接函数调用,对吧?

example:

"test.php?id=100&status=pending&time=2009"
> qd
id: ["100"]
status: ["pending"]
time: ["2009"]

// values can also be obtained like this
> qd.id[0]    // "100"
> qd["id"][0] // "100"

*It returns arrays, because it is optimized for multi-valued keys. Look here for dummy solutions (without arrays).

*它返回数组,因为它针对多值键进行了优化。在这里查看虚拟解决方案(没有数组)。

note: To teach old browsers the new .forEach you can inject this polyfill from Mozilla (MDN).

注意:要教旧浏览器新的.forEach,您可以从Mozilla(MDN)注入此polyfill。

#1


This code:

function querySt(ji) {
    hu = $(".clickme").attr("href");
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

To use it:

要使用它:

document.write(querySt("id"));
document.write(querySt("status"));

Answer to your 'update':

回答您的“更新”:

http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

#2


var stringId = $(this).attr("id"); // this will return p_100
var stringId = $(this).attr("id").split('_')[1]; // this will return 100

var attr= $(this).attr("href"); // this will return all href attribute value

UPDATE

//href="test.php?id=100&status=pending&time=2009"
var attrFromAnchor= $(this).attr("href").split('?')[1].split('&')[0].split('=')[1]; // returns 100

#3


There are a lot of good solutions here but I figured I'd post my own. Here's a quick little function I threw together which will parse a query string in the format from either window.location.search or from a provided search string value;

这里有很多好的解决方案,但我想我会发布自己的解决方案。这是一个快速的小函数,我将它放在一起,它将从window.location.search或提供的搜索字符串值解析格式的查询字符串;

It returns a hash of id value pairs so you could reference it in the form of:

它返回id值对的散列,因此您可以以下列形式引用它:

var values = getQueryParams();
values['id']
values['blah']

Here's the code:

这是代码:

/*
 This function assumes that the query string provided will
 contain a ? character before the query string itself.
 It will not work if the ? is not present.

 In addition, sites which don't use ? to delimit the start of the query string
 (ie. Google) won't work properly with this script.
 */
function getQueryParams( val ) {
    //Use the window.location.search if we don't have a val.
    var query = val || window.location.search;
    query = query.split('?')[1]
    var pairs = query.split('&');
    var retval = {};
    var check = [];
    for( var i = 0; i < pairs.length; i++ ) {
        check = pairs[i].split('=');
        retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
    }

    return retval;
}

To get the value of the query string from the URL without string parsing you can do:

要从URL中获取查询字符串的值而不进行字符串解析,您可以执行以下操作:

window.location.search.substr(1)

If you want the name of the page before the ? you still need to do a little string parsing:

如果你想要之前的页面名称?你还需要做一个小的字符串解析:

var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me

Hope this helps! Cheers.

希望这可以帮助!干杯。

#4


Here's a concise (yet complete) implementation for getting ALL name/value pairs from a query string:

这是一个简洁(但完整)的实现,用于从查询字符串中获取所有名称/值对:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {};
    var tokens;

    while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

#5


No need for jQuery, this solution works on all browsers:

不需要jQuery,这个解决方案适用于所有浏览器:

function querySt(ji)
{
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
    ft = gy[i].split("=");
    if (ft[0] == ji) {
    return ft[1];
    }
    }
    return "";
}

#6


Answers here are outdated now.

这里的答案现在已经过时了。

See this solution using Vanilla JavaScript (ES5)

var qd = {}; // qd stands for query dict
document.getElementById("p_100")[0].href.split("?")[1].split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,]})

I like to pretend it's oneliner, but I was told it's not. hmm...Who would split chained function calls on new lines anyways, right?

我喜欢假装它是oneliner,但我被告知它不是。嗯......无论如何,谁会在新线上拆分链接函数调用,对吧?

example:

"test.php?id=100&status=pending&time=2009"
> qd
id: ["100"]
status: ["pending"]
time: ["2009"]

// values can also be obtained like this
> qd.id[0]    // "100"
> qd["id"][0] // "100"

*It returns arrays, because it is optimized for multi-valued keys. Look here for dummy solutions (without arrays).

*它返回数组,因为它针对多值键进行了优化。在这里查看虚拟解决方案(没有数组)。

note: To teach old browsers the new .forEach you can inject this polyfill from Mozilla (MDN).

注意:要教旧浏览器新的.forEach,您可以从Mozilla(MDN)注入此polyfill。