使用ajax请求每隔x分钟运行一次php脚本

Run php script every x mins using ajax request

本文关键字:一次 脚本 php 运行 请求 ajax 分钟 使用      更新时间:2023-09-26

得到了这个文件'functions.php':

<?php
function test ($url){
$starttime = microtime(true);
$valid = @fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
   echo "Status - Failure";
} else {
   echo "Status - Success";
}
}
    test('google.com');
?>

我想每10秒左右运行一次,有人告诉我要使用ajax请求,但我不完全理解它是如何工作的。我尝试创建一个新文件"index.php",然后在其中写下了以下内容:

<script>
var milliSeconds = 10000; 
setInterval( function() {
    //Ajax request, i dont know how to write it
    xmlhttp.open("POST","functions.php",true);
    xmlhttp.send();
}, milliSeconds);
</script>

我把这两个文件都放进了ftp,但什么都没发生,有人能帮我写一个proper-ajax请求吗?

编辑:编辑打字错误,在上仍然不起作用

var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         console.log ( xmlhttp.responseText );
      } 
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();

}, milliSeconds);

您必须根据浏览器加载xmlhttp请求对象(xmlhttp=new XMLHttpRequest();(,然后在xmlhttp状态更改时设置事件处理程序(xmlhttp.onreadystatechange=function()(。当它改变时,检查状态是否为200(成功(,然后对响应执行任何您想要的操作。(我把它打印到控制台(

所以,听起来您唯一的问题是不知道如何编写XHR请求。看看使用XMLHttpRequest。用你的问题评论这个答案。

xmlhttp.open("POST","funkction.php",true); 

应该是:

xmlhttp.open("POST","functions.php",true);