Rob*_*ohr 41 javascript url get
如果我在一个页面上
http://somesite.com/somepage.php?param1=asdf
在该页面的JavaScript中,我想将一个变量设置为URL的GET部分中的参数值.
所以在JavaScript中:
<script>
param1var = ... // ... would be replaced with the code to get asdf from URI
</script>
Run Code Online (Sandbox Code Playgroud)
会是什么?
Jos*_*lio 96
这是一些示例代码.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
Run Code Online (Sandbox Code Playgroud)
您可以获取位置对象的"搜索"部分 - 然后将其解析出来.
var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
Run Code Online (Sandbox Code Playgroud)
我做了gnarf解决方案的这个变种,所以调用和结果类似于PHP:
function S_GET(id){
var a = new RegExp(id+"=([^&#=]*)");
return decodeURIComponent(a.exec(window.location.search)[1]);
}
Run Code Online (Sandbox Code Playgroud)
但是,由于在函数中调用会减慢进程,因此最好将其用作全局:
window['var_name '] = decodeURIComponent( /var_in_get=([^&#=]*)/.exec(window.location.search)[1] );
UPDATE
当我还在学习JS时,我在更多JS行为中创建了一个更好的答案:
Url = {
get get(){
var vars= {};
if(window.location.search.length!==0)
window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
key=decodeURIComponent(key);
if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
});
return vars;
}
};
Run Code Online (Sandbox Code Playgroud)
这允许仅使用调用Url.get.
示例
url ?param1=param1Value¶m2=param2Value
可以像:
Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"
Run Code Online (Sandbox Code Playgroud)
这是一个snipet:
// URL GET params
url = "?a=2&a=3&b=2&a=4";
Url = {
get get(){
var vars= {};
if(url.length!==0)
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
key=decodeURIComponent(key);
if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
});
return vars;
}
};
document.querySelector('log').innerHTML = JSON.stringify(Url.get);Run Code Online (Sandbox Code Playgroud)
<log></log>Run Code Online (Sandbox Code Playgroud)