Javascript 页面需要刷新才能使用更新的Cookie
我有以下程序:Javascript 页面需要刷新才能使用更新的Cookie,javascript,php,ajax,Javascript,Php,Ajax,我有以下程序: 调用函数fcn1和href到某个页面p1 fcn1从后端SQL读取6个字符串 这6个字符串存储在cookies中 页面p1读取6个cookie并显示结果6个字符串 以上工作正常-问题是p1在显示最新的6个字符串之前需要刷新。饼干很好-我可以在“检查”中的“饼干”下看到。我试着把暂停(x)和location.reload()在p1上 在php构建HTML之前,如何确保Cookie由函数设置 一个解决方案可能是制作另一个ajax,在p1上更新6个字符串,但我不喜欢这个解决方案——
- 调用函数
和href到某个页面fcn1
p1
- fcn1从后端SQL读取6个字符串
- 这6个字符串存储在cookies中
- 页面
读取6个cookie并显示结果6个字符串p1
暂停(x)代码>和location.reload()
在p1
上
在php构建HTML之前,如何确保Cookie由函数设置
一个解决方案可能是制作另一个ajax,在p1
上更新6个字符串,但我不喜欢这个解决方案——看起来像是一对多的步骤。
我不能发布所有的代码,因为总共有几百行。
下面是调用函数和href的按钮(它在索引为j
的for循环中运行):
echo'';
下面是文本在p1中的定义,在p1中它似乎是加载和“旧cookie”的
谢谢
更新1:
<script>
function fcn1(game) {
var gameid = game;
var date = new Date();
date.setTime(+ date + (30 * 86400000)); // Cookie expires in 30 days
document.cookie = "SelectedGame=" + gameid + "; expires=" + date.toGMTString() + "; path=/";
SetStandardGameCategories();
}
</script>
<script language="javascript">
function SetStandardGameCategories() {
$.ajax({
type: "GET",
url: "/content/SetStandardGameServer.php",
data: {},
success: function(data){
}
});
}
</script>
功能fcn1(游戏){
var gameid=游戏;
变量日期=新日期();
date.setTime(+date+(30*86400000));//Cookie将在30天后过期
document.cookie=“SelectedGame=“+gameid+”expires=“+date.togmString()+”;path=/”;
设置标准游戏类别();
}
函数集标准游戏类别(){
$.ajax({
键入:“获取”,
url:“/content/SetStandardGameServer.php”,
数据:{},
成功:函数(数据){
}
});
}
SetStandardGameServer.php
<?php
ob_start();
require("db.php");
if(isset($_COOKIE['SelectedGame'])) {
SaveStandardCategories($_COOKIE['SelectedGame']);
}
?>
您应该等待PHP执行,然后重定向
echo '<span><li><a onclick="fcn1('.$games_id[$j].', \'/cc/p1.php\'); return false;" href="#" id="'.$games_id[$j]. '" value='.$games_id[$j]. '>' .$games_text[$j]. '</a></li></span>';
请注意,我添加了一个新参数。如果您在其他地方使用此函数,并且不想重定向,只需将参数留空。您需要在ajax中的回调函数中重定向。向我们展示fcn1
函数,我将向您展示cookies是如何随页面发送的,如果您不刷新页面,您将无法获得新的cookies。请尝试使用javascript DOM操作更新,而不是在刷新中使用PHP生成html。@HTMLHELL请参阅编辑@RiggsFolly发送新cookie后如何刷新页面?
<?php
ob_start();
require("db.php");
if(isset($_COOKIE['SelectedGame'])) {
SaveStandardCategories($_COOKIE['SelectedGame']);
}
?>
echo '<span><li><a onclick="fcn1('.$games_id[$j].', \'/cc/p1.php\'); return false;" href="#" id="'.$games_id[$j]. '" value='.$games_id[$j]. '>' .$games_text[$j]. '</a></li></span>';
function fcn1(game, redirectURL) {
var gameid = game;
var date = new Date();
date.setTime(+ date + (30 * 86400000)); // Cookie expires in 30 days
document.cookie = "SelectedGame=" + gameid + "; expires=" + date.toGMTString() + "; path=/";
SetStandardGameCategories(redirectURL);
}
function SetStandardGameCategories(redirectURL) {
$.ajax({
type: "GET",
url: "/content/SetStandardGameServer.php",
data: {},
success: function(data){
if (redirectURL) {
window.location.href = redirectURL;
}
}
});
}