Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用JS从url获取变量_Javascript_Jquery_Regex - Fatal编程技术网

Javascript 使用JS从url获取变量

Javascript 使用JS从url获取变量,javascript,jquery,regex,Javascript,Jquery,Regex,可能重复: 我有这个链接 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,

可能重复:

我有这个链接

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]);
})();
它返回未定义的

代码有什么问题?

请在此处使用:

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")
发件人:

我不久前写了这个函数:

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

document.location.href?您的代码刚刚在FF linux中为我工作,没有任何修改…谢谢。。。这对我起作用了