如何在 Javascript 或 jQuery 中获取查询字符串参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30271461/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get query string parameter in Javascript or jQuery?
提问by Headshot
I have a link like this:
我有一个这样的链接:
http://localhost:8162/UI/Link2.aspx?txt_temp=123abc
I want to get the value 123abc. I have followed this How can I get query string values in JavaScript?and 
jquery get querystring from URL
我想获得价值123abc。我遵循了这个如何在 JavaScript 中获取查询字符串值?和 
jquery 从 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"]);
    }  
});
But it does not work.
但它不起作用。
回答by Abhi
Suppose you have URL with many params eg:-
假设您有包含许多参数的 URL,例如:-
"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
Then in js you can do like:
然后在 js 中你可以这样做:
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
OR
或者
var url = window.location.href
then split main url like:
然后拆分主网址,如:
hashes = url.split("?")[1]
//hashes holds this output "txt_temp=123abc&a=1&b=2"
//哈希保存这个输出“txt_temp=123abc&a=1&b=2”
Then again you can split by &to get individual param
然后你可以用&分割来获得单独的参数
EDIT
编辑
Check this example:
检查这个例子:
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;
}
Output
输出
getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
回答by Abhi
It doesn't work because you're running the functions inside of onload, which doesn't fire inside of document.ready, because by the time the code inside of document.readyexecutes, onloadhas already fired. Just get your code out of the onloadevent:
它不起作用,因为您正在运行 内部的函数onload,而内部的函数不会触发document.ready,因为到document.ready执行内部的代码时,onload已经触发了。只需将您的代码从onload事件中取出:
http://jsfiddle.net/whp9hnsk/1/
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"]);
});
回答by Blake A. Nichols
This should get you started:
这应该让你开始:
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 );
回答by aabiro
You can use:
您可以使用:
    var param = new URLSearchParams(urlString).get('theParamName');
Or if searching the current page:
或者如果搜索当前页面:
    var param = new URLSearchParams(location.search).get('theParamName');
回答by Umut Bebek
you have to slice the everything before and after "=" so first answer is a bit incomplete. Here is the answer which works for querystrings includes "=" in it too :) Like:
您必须将“=”前后的所有内容切片,因此第一个答案有点不完整。这是适用于查询字符串的答案,其中也包括“=”:) 喜欢:
https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john
https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john
Thanks to user abhi
感谢用户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;
    }
and then get it with
然后得到它
var url = window.getUrlVars()["returnUrl"];
so it will extract "/writer/user?id=315" with "=" too :)
所以它也会用“=”提取“/writer/user?id=315”:)

