更新
我正在通过ajax发送一个唯一的变量,每次再次提交表单时都需要刷新此变量
我的代码看起来像这样
function refresh_fun() {
/****** PHP ******/
<?php
$GLOBALS['uni_sub'] = uniqid(); // wants to refresh it
?>
}
/****** HTML *******/
<input type="hidden" name="uni_sub" value="<?php echo $uni_sub;?>"> //needs to refresh it too in order to get the same unique refreshed variable
/***** Ajax ******/
success: function(response)
{
refresh_fun(); // this function should change the php variable
}
如果你正在寻找一个每次局部变量值变化时都会显示显示信息的UI,你可以尝试在javascript中使用间隔计时器或使用REACT或Vue。如果您的意思是更改 PHP 变量以反映在页面上(不刷新页面(,那么您绝对不希望每毫秒向服务器发出请求。也许您需要每秒"推送"这些更新。检查关于网络套接字
您可以使用如下所示的 ajax 轮询:
//js
var firstid = 0;
function ajaxpolling(){
$.post('gogetmyuniqueid.php', function(idhere) {
if (firstid != idhere) { // do changes on input if there's update
firstid = idhere;
$("#myhiddeninput").val(idhere);
}
});
}
setTimeout(ajaxpolling(),5000);
但我建议使用 SSE:
// js
var firstid = 0;
var source = new EventSource("gogetmyuniqueid.php");
source.onmessage = function(event) {
if (firstid != event.data) { // do changes on input if there's update
firstid = event.data;
$("#myhiddeninput").val(event.data);
}
};
使用 SSE 的服务器端 (PHP(:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo "data: {uniqueid()}nn";
flush();
?>