Pip*_*ith 2 javascript php cookies ajax jquery
我有一个带有表单的php页面,它有一个按钮.单击该按钮时,将运行jquery函数,该函数执行一些验证测试,然后使用ajax提交表单.在由ajax运行的php脚本中,设置了一个cookie.在设置cookie之后,我立即尝试获取cookie值,我从脚本回显并在ajax请求的成功函数中吐出.cookie值尚未设置.
代码如下.
mainpage.php
<script type="text/javascript">
$( document ).ready(function()
{
$('#submit_compare_stage1').click(function()
{
//Validation stuff
if (passed_validation)
{
var form_data = $('#compare_form').serialize(); //Collect query details into a form
$.ajax({
type: "POST",
url: "scripts/process_compare.php",
data: form_data,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//Error stuff
}
});
}
return false;
});
});
</script>
<form name="compare_form" id="compare_form" action="">
....
<button id='submit_compare_stage1' name='submit_compare_stage1'>Next</button>
</form>
Run Code Online (Sandbox Code Playgroud)
process_compare.php
<?php
//MySQL Stuff
makeCookie('cs', '2');
echo 'hi' . getCookie('cs', false);
echo "success";
function makeCookie($name, $contents, $length = 3600)
{
// Create a new cookie
setcookie($name, $contents, time() + $length, '/');
}
function getCookie($name, $delete = true)
{
// Return the contents of a cookie and delete it if requested
$contents = $_COOKIE[$name];
if($delete) {
setcookie($name, '', time() - 3600, '/');
setcookie($name, '', time() - 3600);
}
return $contents;
}
?>
Run Code Online (Sandbox Code Playgroud)
ajax请求发布警告消息,说"hisuccess",因此cookie未被设置.
我不确定是不是因为页面需要刷新或其他东西,但我知道当我们使用action ="/ process_compare.php"定期提交表单时使用的代码以及将结果放入的iframe.
有人可以帮忙吗?
Cookie作为响应的标头发送.在data参数中,您获得响应的主体,而不是标题.
似乎,响应的标题,您来自getResponseHeader()或MDN - getAllResponseHeaders()不包括Set-Cookie标题.
但是浏览器会透明地处理cookie.因此,为了访问cookie,您可以使用该document.cookie属性
$.ajax({
...
success: function(data, status, jqxhr) {
var cookies = [];
if (document.cookie)
cookies = document.cookie.split('; ');
// do something with the cookies
},
});
Run Code Online (Sandbox Code Playgroud)
或者使用github上提供的jQuery Cookie插件.
| 归档时间: |
|
| 查看次数: |
17207 次 |
| 最近记录: |