将 javascript 数据存储到 PHP SESSION VARIABLE 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23621979/
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
Store javascript data into PHP SESSION VARIABLE?
提问by user3630724
I'm wondering if it's possible to store a number generated from a javascript script into a PHP SESSION variable. I basically want to store my code '+.res.id+' and '+.res.level+' into a PHP SESSION. Those 2 javascript codes generate a random number and inputs that number in a html form. IS there anyway I could take that number and store it in a PHP SESSION? For example
我想知道是否可以将从 javascript 脚本生成的数字存储到 PHP SESSION 变量中。我基本上想将我的代码 '+.res.id+' 和 '+.res.level+' 存储到 PHP SESSION 中。这 2 个 javascript 代码生成一个随机数并以 html 形式输入该数字。无论如何我可以把那个号码存储在一个PHP SESSION中吗?例如
<script>
JAVASCRIPT CODING
'+res.level+'
'+res.id+' // BTW it actually does generate a number I just can't echo it in another page or store it in a SESSION
</script>
<?php
$_SESSION['.res.id.'] = $idnum;
$_SESSION['.res.level.'] = $levelnum;
?>
Then after in a seperate page I want to call that SESSION and echo the number that the code generated. But my only problem is that when I echo the $_SESSION it echo's as ".res.id." instead of the randomly generated number. How do I fix this to make it echo the random generated number?
然后在一个单独的页面之后,我想调用那个 SESSION 并回显代码生成的数字。但我唯一的问题是,当我回显 $_SESSION 时,它回显为“.res.id”。而不是随机生成的数字。如何解决此问题以使其与随机生成的数字相呼应?
回答by Imat
First of all javascript is running on a client side and php is running on a server side. It means you can't just store the generated number. But there is a workaround on that. You can do that by means of AJAX request.
首先,javascript 在客户端运行,而 php 在服务器端运行。这意味着您不能只存储生成的数字。但是有一个解决方法。你可以通过 AJAX 请求来做到这一点。
In your js you can do this.
在您的 js 中,您可以执行此操作。
var res_id = your_random_number;
var res_level = your_random_number
$.post("/any/url/that/contains/your/php/code", {res_id:res_id, res_level:res_level});
In your php.
在你的 php.
$_SESSION["res_id"] = $_POST["res_id"];
$_SESSION["res_level"] = $_POST["res_level"];