gpt4 book ai didi

javascript - 页面需要刷新才能使用更新的 cookie

转载 作者:行者123 更新时间:2023-11-30 20:04:13 24 4
gpt4 key购买 nike

我有以下程序:

  • 调用函数 fcn1 和 href 到某个页面的按钮 p1
  • fcn1从后端SQL读取6个字符串
  • 6个字符串存储在cookie中
  • 页面p1读取6个cookie并显示结果6个字符串

以上工作正常 - 问题是 p1 在显示最新的 6 个字符串之前需要刷新。 cookie 很好 - 我可以在“检查”的“cookie”下看到它。我尝试在 p1 上放入 pause(x);location.reload()

在 php 构建 HTML 之前,如何确保 cookie 由函数设置?

一个解决方案可能是制作另一个 ajax,更新 p1 上的 6 个字符串,但我不喜欢该解决方案 - 似乎是一个到多个步骤。我无法发布所有代码,因为它总共有数百行。下面是调用函数和 href 的按钮(它在索引为 j 的 for 循环中运行):

echo '<span><li><a onclick="fcn1('.$games_id[$j].')" href="/cc/p1.php" id="'.$games_id[$j]. '" value='.$games_id[$j]. '>' .$games_text[$j]. '</a></li></span>';

下面是文本在 p1 中的定义方式,它似乎加载和“旧 cookie”。

<text x="501" y="289.9721" alignment-baseline="middle" text-anchor="middle" font-family="Verdana" font-size="24"><?php echo $_COOKIE["cat1_str"] ?></text>

谢谢

更新 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>

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>';

脚本:

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;
}
}
});
}

请注意,我添加了一个新参数。如果您在其他地方使用此功能,并且不想重定向,则将参数留空即可。

关于javascript - 页面需要刷新才能使用更新的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53086427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com