gettint error 400 with AJAX

时间:2019-09-01 作者:mckvak

你好,我得到错误400。这是我的PHP和JS文件路径。PHP

add_action("wp_enqueue_scripts", "js_enqueue_search");
function js_enqueue_search(){
    wp_register_script("search", get_stylesheet_directory_uri() . "/js/search.js", "", wp_get_theme()->get("Version"), true);
    wp_enqueue_script("search");
    wp_localize_script("search","search_x", array("ajaxurl" => admin_url("admin-ajax.php")));
}

add_action("wp_ajax_nopriv_search_data", "search_data");
add_action("wp_ajax_search_data", "search_data");
function search_data(){
    echo "test";
    wp_die();
}
JS公司

let ajax = new XMLHttpRequest();
ajax.open("GET", search_x.ajaxurl, true);
ajax.send();

ajax.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.ajax);
  }
};

1 个回复
最合适的回答,由SO网友:Ahmad Wael 整理而成

我看不到action 代码中的参数

它应该是:

let ajax = new XMLHttpRequest();
ajax.open("GET", search_x.ajaxurl + \'?action=search_data\', true);
ajax.send();

ajax.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.ajax);
  }
};
请参阅有关动作参数的参考https://codex.wordpress.org/AJAX_in_Plugins