Javascript jquery 从 URL 获取查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4656843/
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
jquery get querystring from URL
提问by Tom
I have the following URL:
我有以下网址:
http://www.mysite.co.uk/?location=mylocation1
What I need is to get the value of location
from the URL into a variable and then use it in a jQuery code:
我需要的是将 的值location
从 URL 获取到变量中,然后在 jQuery 代码中使用它:
var thequerystring = "getthequerystringhere"
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
Does anyone know how to grab that value using JavaScript or jQuery?
有谁知道如何使用 JavaScript 或 jQuery 获取该值?
回答by benhowdle89
From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
来自:http: //jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
This is what you need :)
这就是你需要的:)
The following code will return a JavaScript Object containing the URL parameters:
以下代码将返回一个包含 URL 参数的 JavaScript 对象:
// Read a page's GET URL variables and return them as an associative array.
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;
}
For example, if you have the URL:
例如,如果您有以下网址:
http://www.example.com/?me=myValue&name2=SomeOtherValue
This code will return:
此代码将返回:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
and you can do:
你可以这样做:
var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
回答by Yene Mulatu
To retrieve the entire querystring from the current URL, beginning with the ?
character, you can use
要从当前 URL 检索整个查询字符串,从?
字符开始,您可以使用
location.search
https://developer.mozilla.org/en-US/docs/DOM/window.location
https://developer.mozilla.org/en-US/docs/DOM/window.location
Example:
例子:
// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123"
In regards to retrieving specific querystring parameters, while although classes like URLSearchParams
and URL
exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:
关于检索特定的查询字符串参数,虽然类喜欢URLSearchParams
和URL
存在,但 Internet Explorer 目前不支持它们,应该避免使用。相反,你可以尝试这样的事情:
/**
* Accepts either a URL or querystring and returns an object associating
* each querystring parameter to its value.
*
* Returns an empty object if no querystring parameters found.
*/
function getUrlParams(urlOrQueryString) {
if ((i = urlOrQueryString.indexOf('?')) >= 0) {
const queryString = urlOrQueryString.substring(i+1);
if (queryString) {
return _mapUrlParams(queryString);
}
}
return {};
}
/**
* Helper function for `getUrlParams()`
* Builds the querystring parameter to value object map.
*
* @param queryString {string} - The full querystring, without the leading '?'.
*/
function _mapUrlParams(queryString) {
return queryString
.split('&')
.map(function(keyValueString) { return keyValueString.split('=') })
.reduce(function(urlParams, [key, value]) {
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
urlParams[key] = parseInt(value);
} else {
urlParams[key] = decodeURI(value);
}
return urlParams;
}, {});
}
You can use the above like so:
你可以像这样使用上面的:
// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }
// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }
// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') {
console.log(urlParams.parameterName);
}
回答by James
An easy way to do this with some jQuery and straight JS, just view your console in Chrome or Firefox to see the output...
使用一些 jQuery 和直接 JS 执行此操作的简单方法,只需在 Chrome 或 Firefox 中查看您的控制台即可查看输出...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
回答by Steve
Have a look at this stackoverflow answer.
看看这个stackoverflow 答案。
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
您可以使用该方法来制作动画:
ie:
IE:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
回答by Adriano Galesso Alves
We do this way...
我们这样做...
String.prototype.getValueByKey = function (k) {
var p = new RegExp('\b' + k + '\b', 'gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};