php 如何使用 jQuery + AJAX 更新 SESSION 变量,甚至可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9650930/
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
How to update SESSION variable with jQuery + AJAX, is it even possible?
提问by Drazek
I would like to update session variable.
我想更新会话变量。
Let me introduce this in simple example. We get a div with input fields printed out by PHP script, with some values etc...
让我用简单的例子来介绍一下。我们得到一个带有由 PHP 脚本打印出的输入字段的 div,带有一些值等......
Example PHP code:
示例 PHP 代码:
echo '
<div id="few-input-fields">
<input id="Name" size="20" value="' . $_SESSION['name'] . '" />
<br />
<input id="Lastname" size="20" value="' . $_SESSION['lastname'] . '" />
</div>
<span id="save">save</span>
</div>
';
Let's say user edit this input field (id=Name) and type name "Mark" inside it and then press save text.
假设用户编辑此输入字段 (id=Name) 并在其中键入名称“Mark”,然后按保存文本。
On click it should save/update session variable, without reloading page AND refresh input fields.
单击它应该保存/更新会话变量,无需重新加载页面和刷新输入字段。
Is that possible? Perhaps with ajax / jquery? And most importantly how ?
那可能吗?也许用ajax/jquery?最重要的是如何?
回答by Christofer Eliasson
Yes, just do a simple AJAX request. With jQuery it would be:
是的,只需做一个简单的 AJAX 请求。使用 jQuery,它将是:
$("#formid").submit(function(){
$.ajax({
type: "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(){
// Do what you want to do when the session has been updated
}
});
return false;
});
And your PHP:
还有你的 PHP:
<?php
session_start();
$_SESSION["name"] = $_POST["name"];
// Add the rest of the post-variables to session-variables in the same manner
?>
Note
笔记
You need to add name-attributes to your input-fields.
您需要将名称属性添加到您的输入字段。