2016-04-21 51 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(); 
}