问题描述
想要在不刷新页面的情况下更改 SESSION 变量fullname"的值.
Want to change value of SESSION variable "fullname" without refreshing the page.
我使用ajax的实现:
My implementation using ajax:
第 1 页 html:
Page 1 html:
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
第 1 页脚本:
<script>
function setSession(){
var fullname = $("#fullname").val();
var dataString = 'fullname=' + fullname;
$.ajax({
type: "POST",
url: "Page2.php",
data: dataString,
cache: false,
success: function( data ) {
if(data === 'True'){
alert("<?php echo $_SESSION['fullname'];?>");
}
}
});
}
</script>
在第 2 页:
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'True';
exit();
它不会改变会话变量的值.
It doesn't change the value of the session variable.
两个页面都有 session_start().
Both pages have session_start().
推荐答案
您的代码应该已经在更改 PHP 会话中的值.您只是没有正确设置客户端脚本来显示这一点.
Your code should already be changing the value in the PHP session. You just don't have your client-side script set up properly to show that.
在您的 PHP 脚本中返回某种指标:
Return some kind of indicator in your PHP script:
<?php
// Page2.php
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'set session fullname to ' . $_POST['fullname'];
然后在您的 AJAX 成功函数中,显示该响应:
Then in your AJAX success function, show that response:
...
success: function( response ) {
alert(response);
}
...
当您在成功函数中使用 alert("<?php echo $_SESSION['fullname'];?>");
时,PHP 将填充 $_SESSION['fullname']
页面加载时该警报框中的值一次,并且在页面重新加载之前永远不会更改,即使您通过 AJAX 成功更新了会话值.
When you use alert("<?php echo $_SESSION['fullname'];?>");
in your success function, PHP will fill in the $_SESSION['fullname']
value in that alert box once when the page loads, and it will never change until the page is reloaded, even if you do successfully update the session value via AJAX.
这篇关于使用 ajax 设置 PHP 会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!