我正在使用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>
我测试了要显示的文件
我不确定我错过了什么才能让电话工作。
注意:您需要将 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();
}