-3

可能重复:
如何获取查询字符串值?

我有这个链接

url/merchant.html?id=45

我正在尝试使用 JS 或 JQuery 获取 ID,但没有成功。

我试过这段代码

var urlParams = {};
(function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

它返回“未定义”

代码有什么问题?

4

2 回答 2

1

在这里使用这个:

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

所以在你的情况下:

getParameterByName("id")

来自: 如何在 JavaScript 中获取查询字符串值?

于 2013-01-11T16:27:12.207 回答
0

我不久前写了这个函数:

/**
 * Retrieves the value of a query string parameter.
 * @param string href The full URL
 * @param string key The key in the query string to search for.
 * @param variant def The default value to return if the key doesn't exist.
 * @returns variant if key exists returns the value, otherwise returns a default value.
 */
function getURIParam(href, key, def) {
    if (arguments.length == 2) def = null;
    var qs = href.substring(href.indexOf('?') + 1);
    var s = qs.split('&');
    for (var k in s) {
        var s2 = s[k].split('=');
        if (s2[0] == key)
            return decodeURIComponent(s2[1]);
    }
    return def;
}

你会像这样使用它:

var href = "http://www.example.org?id=1492";
var id = getURIParam(href, "id", 0);
//Output of id: 1492

如果密钥不存在:

var href = "http://www.example.org?id=1492";
var name = getURIParam(href, "name", "Unnamed");
//Output of name: Unnamed
于 2013-01-11T16:27:50.857 回答