带有Wordpress AJAX调用的400错误请求

时间:2018-09-20 22:36:11

标签: php wordpress

我正在为Wordpress网站的前端开发搜索插件。目前,我不断收到400错误的请求错误,我不明白为什么。我已经审查了关于SO和WordpressStackExchange的许多问题,但看不到我要去哪里,似乎没有什么错位。请给我指导:

plugin.php:

function my_admin_scripts() {
    $localize = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );

    wp_register_script('veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', '', '', true);

    wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);

    wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
}  

add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'handle_request' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'handle_request' ); 

    //takes care of the $_POST data
function handle_request(){
    echo "hello";
}

ajax.js

    var data = {
        action: 'handle_request',
        RequestType: 'category',
        Category:  jQuery('#Category option:selected').val()
    };

    jQuery.post(
        veh_app_script.ajaxurl,
        data,
        function(categories){
            console.log(categories);
        }
    );

有人希望在控制台中看到“ Hello”,但我只会在控制台中看到错误:

jquery.js?ver=1.12.4:4 POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request)

2 个答案:

答案 0 :(得分:2)

请替换代码并检查

plugin.php

function my_admin_scripts() {
    $localize = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );

    wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );

    wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);


}  

add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' ); 

    //takes care of the $_POST data
function handle_request(){
    echo "hello";
}

ajax.js

var data = {
        action: 'handle_request',
        RequestType: 'category',
        Category:  jQuery('#Category option:selected').val()
    };

    jQuery.post(
        veh_app_script.ajaxurl,
        data,
        function(categories){
            console.log(categories);
        }
    );

答案 1 :(得分:0)

改为使用JSON:

function handle_request(){
  echo json_encode( array( "message" => "hello" ) );
  exit;
}

在您的ajax.js响应处理程序中解析JSON:

function( response ) {
  var returndata = JSON.parse( response );
  console.log( returndata.message );
}

不要忘记将json2添加为脚本的依赖项。

wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery', 'json2' ) );