我见过很多jQuery示例,其中参数大小和名称都是未知的。

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

sent存在吗? 它等于"是"吗?


当前回答

var RequestQuerystring; (窗口。Onpopstate = function () { var匹配, pl = /\+/g, //用空格替换加法符号的正则表达式 搜索= /([^&=]+)=?([^&]*)/g, decode =函数(s){返回decodeURIComponent(s)。替换(pl, " "));}, Query = window.location.search.substring(1); RequestQuerystring = {}; While (match = search.exec(查询)) RequestQuerystring[decode(match[1])] = decode(match[2]); })();

RequestQuerystring现在是一个包含所有参数的对象

其他回答

使用普通JavaScript,您可以很容易地获取参数(location.search),获得子字符串(不带?),并通过'&'分隔它,将其转换为数组。

当你遍历urlParams时,你可以再次用'='分割字符串,并将其添加到'params'对象中,作为object[elmement[0]] = element[1]。超级简单,易于访问。

http://www.website.com/?error=userError&type=handwritten

            var urlParams = location.search.substring(1).split('&'),
                params = {};

            urlParams.forEach(function(el){
                var tmpArr = el.split('=');
                params[tmpArr[0]] = tmpArr[1];
            });


            var error = params['error'];
            var type = params['type'];

函数GetRequestParam(参数) { Var res = null; 尝试{ var qs = decodeURIComponent(window.location.search.substring(1));//获取then之后的所有内容'?URI中的' Var ar = q .split('&'); 美元。Each (ar, function(a, b){ Var kv = b.split('='); If (param === kv[0]){ Res = kv[1]; 返回false;//打破循环 } }); }捕捉(e) {} 返回res; }

使用URLSearchParams:

var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));

注意兼容性(大多数情况下是好的,但IE和Edge,可能是不同的故事,检查这个兼容性参考:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

我希望这能有所帮助。

 <script type="text/javascript">
   function getParameters() {
     var searchString = window.location.search.substring(1),
       params = searchString.split("&"),
       hash = {};

     if (searchString == "") return {};
     for (var i = 0; i < params.length; i++) {
       var val = params[i].split("=");
       hash[unescape(val[0])] = unescape(val[1]);
     }

     return hash;
   }

    $(window).load(function() {
      var param = getParameters();
      if (typeof param.sent !== "undefined") {
        // Do something.
      }
    });
</script>

还有一个使用URI.js库的例子。

例子准确地回答了所问的问题。

var url = 'http://example.com?sent=yes'; var urlParams = new URI(url).search(true); // 1. Does sent exist? var sendExists = urlParams.sent !== undefined; // 2. Is it equal to "yes"? var sendIsEqualtToYes = urlParams.sent == 'yes'; // output results in readable form // not required for production if (sendExists) { console.log('Url has "sent" param, its value is "' + urlParams.sent + '"'); if (urlParams.sent == 'yes') { console.log('"Sent" param is equal to "yes"'); } else { console.log('"Sent" param is not equal to "yes"'); } } else { console.log('Url hasn\'t "sent" param'); } <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>