2016-04-21 52 views
0

我正在使用WordPress &试图添加一些AJAX。WordPress Ajax调用不起作用

我在[模板]文件/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> 

我有测试显示在

的文件,我不知道我的思念让调用工作。

+0

您确定在点击按钮时加载了您的JS代码吗? –

+0

同样值得关注的是,在WordPress中处理AJAX请求的admin-ajax.php方法。 – shmuli

回答

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(); 
}