For GET parameters, you can grab them from document.location.search
:
(对于GET参数,您可以从document.location.search
获取它们:)
var $_GET = {};
document.location.search.replace(/??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST
object in JSON format into a <script>
tag:
(对于POST参数,您可以将JSON格式的$_POST
对象序列化为<script>
标记:)
<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["test"]);
</script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
(当你在它(在服务器端做事)时,你也可以在PHP上收集GET参数:)
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode
function.
(注意:您需要PHP 5或更高版本才能使用内置的json_encode
函数。)
Update: Here's a more generic implementation:
(更新:这是一个更通用的实现:)
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…