【问题标题】:How can I get query string parameter in Javascript or jQuery?如何在 Javascript 或 jQuery 中获取查询字符串参数?
【发布时间】:2015-07-28 02:00:59
【问题描述】:

我有一个这样的链接:

http://localhost:8162/UI/Link2.aspx?txt_temp=123abc

我想得到 123abc 的值。我关注了这个How can I get query string values in JavaScript?jquery get querystring from URL

$(document).ready(function () {
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    onload = function () {
        alert(getParameterByName('txt_temp'));
        alert(getUrlVars()["txt_temp"]);
    }  
});

但它不起作用。

【问题讨论】:

  • 当您说它不起作用时,您会得到什么结果?什么都没有或值错误?
  • @Val : 这里没有提醒,谢谢

标签: javascript jquery url


【解决方案1】:

假设您的 URL 包含许多参数,例如:-

"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"

然后在js中你可以这样做:

var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"

var url = window.location.href

然后拆分主网址,如:

hashes = url.split("?")[1]

//hashes 保存这个输出 "txt_temp=123abc&a=1&b=2"

然后你又可以用 & 分割得到单独的参数

编辑

检查这个例子:

function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');

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

输出

getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}

【讨论】:

  • 亲爱的 Abhi,正如你所说,它看起来像 ``` function getUrlVars() { var url = window.location.href; var vars = [],哈希; var hashes = url.split("?")[1]; for (var i = 0; i
  • 定义为var vars = {} 然后vars[hash[0]] = hash[1]
  • 哦不,好像不行。 function getUrlVars() { var url = window.location.href; var vars = [], hash; var hashes = url.split("?")[1]; for (var i = 0; i &lt; hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash); vars[hash[0]] = hash[1]; } return vars; } alert(getUrlVars()["txt_temp"]); alert(getUrlVars()["a"]);
  • 您仍在定义vars = [],而是使用vars = {} 然后尝试
  • 你试过了吗?我认为它不起作用。 function getUrlVars() { var url = window.location.href; var vars = {}, hash; var hashes = url.split("?")[1]; for (var i = 0; i &lt; hashes.length; i++) { hash = hashes[i].split('&amp;'); vars.push(hash); vars[hash[0]] = hash[1]; } return vars; } alert(getUrlVars()["txt_temp"]); alert(getUrlVars()["a"]); 不行。谢谢各位。
【解决方案2】:

它不起作用,因为您正在运行 onload 内部的函数,它不会在 document.ready 内部触发,因为当 document.ready 内部的代码执行时,onload 已经被解雇了。 只需将您的代码从onload 事件中取出:

http://jsfiddle.net/whp9hnsk/1/

$(document).ready(function() {

   // Remove this, this is only for testing.
   history.pushState(null, null, '/UI/Link2.aspx?txt_temp=123abc');

   function getUrlVars() {
       var vars = [],
           hash;
       var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
       for (var i = 0; i < hashes.length; i++) {
           hash = hashes[i].split('=');
           vars.push(hash[0]);
           vars[hash[0]] = hash[1];
       }
       return vars;
   }

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

   // You may also place this inside of a function,
   // and execute it when you desire, but `onload` is not going
   // to fire by itself, when inside of document.ready
   alert(getParameterByName('txt_temp'));
   alert(getUrlVars()["txt_temp"]);

});

【讨论】:

    【解决方案3】:

    这应该让你开始:

    function parseQueryStr( str, obj ) {
    
    
        // Return object
        obj = obj || {};
    
    
        // Looping through our key/values
        var keyvalues = str.split('&');
        for( var i=0; i<keyvalues.length; i++ ) {
    
    
            // Break apart our key/value
            var sides = keyvalues[i].split( '=' );
    
    
            // Valid propery name
            if( sides[0] != '' ) {
    
    
                // Decoding our components
                sides[0] = decodeURIComponent( sides[0] );
                sides[1] = decodeURIComponent( sides.splice( 1, sides.length-1 ).join( '=' ) );
    
    
                // If we have an array to deal with
                if( sides[0].substring( sides[0].length - 2 ) == '[]' ) {
                    var arrayName = sides[0].substring( 0, sides[0].length - 2 );
                    obj[ arrayName  ] = obj[ arrayName  ] || [];
                    obj[ arrayName ].push( sides[1] );
                }
    
    
                // Single property (will overwrite)
                else {
                    obj[ sides[0] ] = sides[1];
                }
            }
        }
    
    
        // Returning the query object
        return obj;
    }
    
    var href = window.location.href.split('#');
    var query = href[0].split('?');
    query.splice(0,1);
    var get = parseQueryStr(query.join('?'));
    
    alert( get.txt_temp );
    

    【讨论】:

      【解决方案4】:

      你可以使用:

          var param = new URLSearchParams(urlString).get('theParamName');
      

      或者如果搜索当前页面:

          var param = new URLSearchParams(location.search).get('theParamName');
      

      【讨论】:

        【解决方案5】:

        您必须在“=”之前和之后对所有内容进行切片,所以第一个答案有点不完整。这是适用于查询字符串的答案,其中也包含“=”:) 喜欢:

        https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john

        感谢用户abhi

        var getUrlVars = function () {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]); //to get name before =
                    vars[hash[0]] = hashes[i].slice(hashes[i].indexOf('=') + 1); //to take everything after first =
                }
                return vars;
            }
        

        然后得到它

        var url = window.getUrlVars()["returnUrl"];
        

        所以它也会用“=”提取“/writer/user?id=315” :)

        【讨论】:

          【解决方案6】:

          我用 ES6 语法编写了这一行,它遵循公认答案的方法。

          function getParam(key){
              return window.location.href.split('?')[1].split('&').filter(x=>x.split('=')[0]==key)[0].split('=')[1];
          }
          

          用途:

          假设当前 URL 是:https://stackoverflow.com?question=30271461

          getParams('question') //30271461
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-06-24
            • 2017-07-20
            • 2017-02-08
            相关资源
            最近更新 更多