[英]assigning a $_GET variable to a JS variable
www.mywebsite.com/?foo=bar
如何将foo的值转换为Javascript变量?
You don't even need PHP for that. 您甚至不需要PHP。 Basically, you can parse
window.location.href
to get the value of a GET URL parameter into a JavaScript variable. 基本上,您可以解析
window.location.href
以将GET URL参数的值转换为JavaScript变量。
There is plenty of code online, you can use for example this : 有大量的代码在网上,你可以使用例如这个 :
function getUrlParameter( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
To get the value of foo
, just call getUrlParameter("foo")
in your JavaScript code. 要获取
foo
的值,只需在您的JavaScript代码中调用getUrlParameter("foo")
。
You can parse the window.location.search
string for query variables. 您可以解析
window.location.search
字符串以获取查询变量。
https://developer.mozilla.org/en/DOM/window.location https://developer.mozilla.org/en/DOM/window.location
For example 例如
var query = window.location.search.substring(1);
var pairs = query.split('&');
var _get = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
_get[pair[0]] = pair[1];
}
You can try this 你可以试试这个
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;
}
EDIT 编辑
The above will parse the URL and give you the parameters as an associative array. 上面的代码将解析URL,并为您提供作为关联数组的参数。 You can also try
您也可以尝试
function getURLVars(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
In this if you want the value of foo
, call this with getUrlVars('foo')
在这种情况下,如果需要
foo
的值,请使用getUrlVars('foo')
调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.