因此,我一直在开发一个我正在构建的自定义主题,我正试图实现一个基于AJAX的搜索演示。我已经根据一些教程和指南构建了所有内容,但在检查对admin ajax的调用时,它会不断返回400个错误。。。我没有什么想法,希望有人能对这个问题有所了解。
functions.php
function load_search_results(){
$q = $_REQUEST[\'query\'];
$post_type = $_REQUEST[\'post_type\'];
$args = array(
\'post_type\' => $post_type,
\'post_status\' => \'publish\',
\'s\' => $q,
);
$search = new WP_Query($args);
if ($search->have_posts()){
echo json_encode(\'has posts\');
} else {
echo json_encode(\'no posts found\');
}
wp_die();
}
add_action(\'wp_ajax_load_search_results\', \'load_search_results\');
add_action(\'wp_ajax_nopriv_load_search_results\', \'load_search_results\');
Enqueueing the scripts in functions.php as well
wp_register_script(\'ajax-search\', THEME_DIR .\'/assets/js/ajax/search.ajax.js\', array(\'jquery\'), \'1.0\', false);
wp_enqueue_script(\'ajax-search\');
wp_localize_script(\'ajax-search\', \'myAjax\', array(\'ajax_url\' =>admin_url(\'admin-ajax.php\')));
search.ajax.js
(function($) {
$(document).on(\'submit\', \'.controls-search\', function(){
var $form = $(this);
var $input = $form.find(\'input[name="s"]\');
var query = $input.val();
var $content = $(\'.licence\');
$.ajax({
type: \'POST\',
post_type: \'shuffle_licence\',
url: myAjax.ajax_url,
data: {
action: \'load_search_results\',
query: query
},
beforeSend: function(){
$input.prop(\'disabled\', true);
$content.addClass(\'loading\')
},
succes: function(response){
$input.prop(\'disabled\', false);
$content.removeClass(\'loading\');
$content.html(response);
},
dataType: \'html\',
contentType: \'application/json\',
});
return false;
});
}(jQuery))