如何使用 jQuery 或纯 JavaScript 获取 URL 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19491336/
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 to get URL parameter using jQuery or plain JavaScript?
提问by LeBlaireau
I have seen lots of jQuery examples where parameter size and name are unknown.
我见过很多参数大小和名称未知的 jQuery 示例。
My URL is only going to ever have 1 string:
我的 URL 只会有 1 个字符串:
http://example.com?sent=yes
I just want to detect:
我只想检测:
- Does
sent
exist? - Is it equal to "yes"?
- 是否
sent
存在? - 是否等于“是”?
回答by Sameer Kazi
Best solution here.
最佳解决方案在这里。
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
And this is how you can use this function assuming the URL is,http://dummy.com/?technology=jquery&blog=jquerybyexample
.
这就是假设 URL 为http://dummy.com/?technology=jquery&blog=jquerybyexample
.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
回答by Optio
Solution from 2020
2020年的解决方案
We have: http://example.com?sent=yes
我们有:http: //example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sentexist?
不派存在?
searchParams.has('sent') // true
Is it equalto "yes"?
是否等于“是”?
let param = searchParams.get('sent')
and then just compare it.
然后只是比较它。
回答by Reza Baradaran Gazorisangi
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
jQuery 代码片段,用于获取存储在 url 中的动态变量作为参数,并将它们存储为 JavaScript 变量,以便与您的脚本一起使用:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
example.com?param1=name¶m2=&id=6
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
带空格的示例参数
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
回答by AwokeKnowing
I always stick this as one line. Now params has the vars:
我总是坚持这一行。现在 params 有 vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
多线:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
作为函数
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
您可以将其用作:
getSearchParams() //returns {key1:val1, key2:val2}
or
或者
getSearchParams("key1") //returns val1
回答by rodnaph
Yet another alternative function...
另一个替代功能......
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
回答by Sariban D'Cl
May be its too late. But this method is very easy and simple
可能为时已晚。但是这个方法非常简单简单
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet
更新
需要 url 插件:plugins.jquery.com/url
谢谢 -Ripounet
回答by Qwerty
Or you can use this neat little function, because why overcomplicated solutions?
或者您可以使用这个简洁的小功能,因为为什么解决方案过于复杂?
function getQueryParam(param, defaultValue = undefined) {
location.search.substr(1)
.split("&")
.some(function(item) { // returns first occurence and stops
return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
})
return defaultValue
}
which looks even better when simplified and onelined:
简化和单行时看起来更好:
tl;dr one-line solution
tl;dr 单线解决方案
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result: queryDict['sent'] // undefined or 'value'
But what if you have got encoded charactersor multivalued keys?
但是如果你有编码字符或多值键怎么办?
You better see this answer: How can I get query string values in JavaScript?
你最好看看这个答案:如何在 JavaScript 中获取查询字符串值?
Sneak peak
潜行高峰
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst?le%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=st?le&car=saab"]
> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
回答by Xin
Using URLSearchParams
:
使用URLSearchParams
:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));
Be careful about the compatibility (Mostly it's fine, but IE and Edge, may be different story, check this for compatible reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
注意兼容性(大多数情况下没问题,但 IE 和 Edge,可能是不同的故事,请检查此兼容性参考:https: //developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
回答by Shuhad zaman
This one is simple and worked for me
这个很简单,对我有用
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
so if your url is http://www.yoursite.com?city=4
所以如果你的网址是http://www.yoursite.com?city=4
try this
尝试这个
console.log($.urlParam('city'));
回答by kelvintaywl
Perhaps you might want to give Dentist JSa look? (disclaimer: I wrote the code)
也许您可能想看看Dentist JS?(免责声明:我写了代码)
code:
代码:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
使用 Dentist JS,您基本上可以在所有字符串(例如 document.URL.extract() )上调用 extract() 函数,然后您将返回找到的所有参数的 HashMap。它还可以自定义以处理分隔符和所有内容。
Minified version < 1kb
缩小版 < 1kb