簡體   English   中英

WordPress Ajax通話不起作用

[英]WordPress Ajax Call not working

我正在使用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(); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM