【问题标题】:Get Variable from the url using JS [duplicate]使用JS从url获取变量[重复]
【发布时间】:2013-01-11 16:24:31
【问题描述】:

可能重复:
How can I get query string values?

我有这个链接

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

它返回“未定义”

代码有什么问题?

【问题讨论】:

  • document.location.href ?
  • 您的代码在 FF linux 中为我工作,无需任何修改...

标签: javascript jquery regex


【解决方案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")

来自: How can I get query string values in JavaScript?

【讨论】:

  • 谢谢...这对我有用
【解决方案2】:

我不久前写了这个函数:

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

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2017-03-24
    • 1970-01-01
    • 2014-09-16
    • 2021-02-09
    • 2013-05-08
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多