首页 > 解决方案 > 使用ajax运行PHP文件

问题描述

当 JS 文件运行时(并且每 4 秒循环一次),我试图让 .PHP 文件从 .JS 文件运行。下面的代码不起作用。我想知道它是否与 WordPress 中的文件链接有关?我对 JS 很陌生,但尽我所能学习。

$(document).ready(function(){
      setInterval(function() {
           alert("Database updated");
          
     var xhttp = new XMLHttpRequest();
     xhttp.open("GET", "tb-user.php", true);
    }, 4000);
});

标签: javascriptajaxwordpress

解决方案


您应该使用正确的 http 请求样式。用这个。

$(document).ready(function(){
      setInterval(function() {
         alert("Database updated");
          
         var xhttp = new XMLHttpRequest();
         xhttp.open("GET", "tb-user.php", true);
         xhttp.onreadystatechange = function() { 
           if (xhttp.readyState == 4 && xhttp.status == 200)
              console.log(xhttp.responseText);
         }
         xhttp.open("GET", "tb-user.php", true); // true for asynchronous 
         xhttp.send();
        }, 4000);
});

推荐阅读