WordPress Ajax调用无法正常工作

时间:2016-04-21 16:58:51

标签: php ajax wordpress

我正在使用WordPress&试图添加一些AJAX。

我在[template] /js/ajax.js

中有一个文件
  function readSearch(){        
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      alert(xhttp.status);
    if (xhttp.readyState == 4 && xhttp.status == 200) {         
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("POST", "ajax_info.php", true);
  xhttp.send(); 
}

我已经把ajax_info.php放在任何地方,当点击按钮时我仍然会得到 xhttp.status == 404

<p class="submit"><input type="submit" name="submit" id="submit" 
    class="button button-primary" value="Leave it to chance" onclick="readSearch()" /></p>

我测试了要在

中显示的文件

我不确定我错过了什么来接听电话。

1 个答案:

答案 0 :(得分:0)

注意:您需要将php文件的完整路径添加为:

有两种方法可以做到:

1)手动提及路径:

 function readSearch(){        
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      alert(xhttp.status);
    if (xhttp.readyState == 4 && xhttp.status == 200) {         
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("POST", "wp-content/themes/template_name/ajax_info.php", true);
  xhttp.send(); 
}

2)使用WordPress函数添加路径(以动态方式工作):

 function readSearch(){        
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      alert(xhttp.status);
    if (xhttp.readyState == 4 && xhttp.status == 200) {         
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("POST", <?php echo get_template_directory_uri()."/ajax_info.php"; ?>, true);
  xhttp.send(); 
}
相关问题