【问题标题】:How to retrieve query string parameter and values using javascript (Jquery)?如何使用 javascript (Jquery) 检索查询字符串参数和值?
【发布时间】:2010-11-13 09:22:24
【问题描述】:

点我

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

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

我正在使用 Jquery。

感谢您的帮助。

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

【问题讨论】:

  • 您需要对其进行子串化。如果您需要示例,请发表评论。

标签: php javascript jquery query-string anchor


【解决方案1】:

这段代码:

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];
        }
    }
}

使用它:

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

回答你的“更新”:

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

【讨论】:

  • 好的..所以我必须通过for循环找到它?我在想我可以直接访问它.. 类似 attr("status")!!!
  • 现在可以了,只需执行 querySt("status");我认为 jQuery 没有内置的 URI 解析函数。
  • 这将适用于除 id 之外的所有内容。使用此代码的关键是“test.php?id”而不是“id”。您需要先删除“?”之前的所有内容。然后在&符号上拆分。
  • 在里面加入一些 decodeURIComponent 调用怎么样?
【解决方案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

更新

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

【讨论】:

  • 感谢您的回答..我可以从元素的 ID 中获取值(已经完成)..但我需要从 Anchor 的 URL 中获取它。
【解决方案3】:

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

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

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

代码如下:

/*
 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;
}

要在不解析字符串的情况下从 URL 中获取查询字符串的值,您可以这样做:

window.location.search.substr(1)

如果你想要页面的名称在 ?你还需要做一些字符串解析:

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

希望这会有所帮助! 干杯。

【讨论】:

  • 此实现不考虑 URL 编码的名称和值。
  • @Ates Goral 你是绝对正确的。它没有考虑这种情况。我已根据您的建议更新了我的解决方案。
  • 如果初始化后没有查询字符串,也应该添加一个条件,即。 if (!query) return [];query.split('?')[1] 行之前
【解决方案4】:

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

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);

【讨论】:

  • 单行正则表达式不适用于 safari 和 IE(无限循环)。解决方法是为“var pattern = /[?&]?([^=]+)=([^&]*)/g;”设置一个单独的行,然后使用“pattern.exec(qs)”。顺便说一句,“qs.split('+')”是干什么用的?如果url是编码的,应该没有加号。
【解决方案5】:

无需 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】:

    这里的答案现在过时了。

    使用 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,]})
    

    我喜欢假装它是 oneliner,但有人告诉我不是。 hmm...谁会在新行上拆分链式函数调用,对吧?

    示例:

    "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"
    

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多