直接从 JavaScript 访问 GET?
我想我可以使用 PHP 从 JavaScript 访问 $_GET
变量:
I suppose I could use PHP to access $_GET
variables from JavaScript:
<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>
但也许更简单.有没有办法直接从JS做到这一点?
But perhaps it's even simpler. Is there a way to do it directly from JS?
推荐答案
看
window.location.search
它将包含这样的字符串:?foo=1&bar=2
It will contain a string like this: ?foo=1&bar=2
要将其转化为对象,您只需要进行一些拆分:
To get from that into an object, some splitting is all you need to do:
var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split("=");
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
alert($_GET['foo']); // 1
alert($_GET.bar); // 2
相关文章