前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button class="btn1">按钮1</button>
<button class="btn2">按钮2</button>
<script>
let oBtn1 = document.querySelector('.btn1'),
oBtn2=document.querySelector('.btn2');
// 按钮1单击事件
oBtn1.onclick = function () {
// 前端设置cookie
let d = new Date();
// 设置cookie保留时间为1分钟
d.setMinutes(d.getMinutes + 1);
// 前端js设置cookie
document.cookie = `test=123;expires=${d.toUTCString()}`;
// 在控制台打印前端cookie
console.log(document.cookie);
// ajax传给后端
let xhr = new XMLHttpRequest();
xhr.open('get', './test.php');
xhr.send();
xhr.onreadystatechange = function () {
// 当http请求成功执行
if (this.status == 200 && this.readyState == 4) {
// 在控制台打印传回来的数据
console.log(this.responseText);
}
}
// 在控制台打印前端cookie
console.log(document.cookie);
}
// 按钮2单击事件
oBtn2.onclick=function(){
console.log(document.cookie);
}
</script>
</body>
</html>
后端php代码:
<?php
// 修改cookie
setcookie("test","666");
// 获取cookie
$test=$_COOKIE["test"];
// 传值给前端ajax
echo $test;
点击按钮1后
控制台结果图
cookie结果图
请求头和响应头结果图
点击按钮2后
控制台结果图
问题:本因应该在控制台的第三行打印‘666’,因为php(是从上到下执行顺序)修改了cookie,并且重新获取cookie,并且传回给前端,而前端
这个位置应该打印‘666’而不是‘123’。