使用AJAX发布到PHP,并在更改后刷新 [英] POST to PHP using AJAX and refresh upon change
问题描述
我正在尝试构建一个Web应用程序,当数据库发生更改时,该应用程序需要刷新整个页面.我想使用AJAX和PHP实现此目的.我想每5秒钟将一条信息发布到PHP脚本中,如果PHP脚本返回的值与预定义变量不同,我想刷新整个页面.
I am trying to build a web application that needs to refresh the entire page when there is a change in the database. I would like to achieve this using AJAX and PHP. I would like to POST a single piece of information to the PHP script every 5 seconds and if the returned value from the PHP script is different from a predefined variable, I would like to refresh the entire page.
例如,我在javascript中的预定义值为200.如果PHP脚本返回了另一个值,我想刷新整个页面.
For example, I have a predefined value in javascript of 200. If the PHP script returns a different value, I would like to refresh the entire page.
我知道如何编写PHP,这只是我遇到问题的XJAX.如果可能的话,我也不想使用jquery.
I know how to write the PHP, it is just the XJAX I am having issues with. I would also not like to use jquery if possible.
谢谢您的指导!
我不希望使用jquery或任何其他框架,而只是原始javascript.我还需要在更改后刷新整个页面,并每5秒钟运行AJAX.
EDIT : I would not like to use jquery or any other framework, just raw javascript. I also need to refresh the entire page upon change and run the AJAX every 5 seconds.
推荐答案
好问题.您可以执行 if(xmlhttp.responseText!==<?php echo $ currentValue;?>"){
来检查PHP端的值是否已更改.通过 setInterval
将这种 watchdog
方法调用非常短的5秒钟.如果有更改,则通过 document.location.reload(true)
(
Good question. You can do if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
to check if the PHP-side value has changed. This watchdog
method is called very 5 seconds through setInterval
. If there is a change, then the page is refreshed via document.location.reload(true)
(ref) to prevent reusing the cache.
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 5 seconds
setInterval(function(){ watchdog(); }, 5000);
注意:我选择了 setInterval
而不是 setTimeout
,因为如果与服务器的连接失败(500错误,超时等),则响应逻辑可能否则无法触发另一个 setTimeout
. setInterval
确保无论连接失败如何,都对服务器进行一致的轮询.
Note: I chose setInterval
over setTimeout
because if the connection to the server fails (500-error, timeout, etc.), then the response logic may otherwise fail to trigger another setTimeout
. setInterval
ensures the server is polled consistently regardless of connection failures.
这篇关于使用AJAX发布到PHP,并在更改后刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!