Wordpress AJAX 调用出现 400 错误请求

Dan*_*iel 2 php wordpress

我正在为 WordPress 网站的前端开发一个搜索插件。目前我不断收到 400 Bad Request 错误,但我不明白为什么。我已经审查了许多关于 SO 和 WordpressStackExchange 的问题,但看不出我哪里出了问题,似乎没有什么不合适的地方。请给我指导:

插件.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";
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    );
Run Code Online (Sandbox Code Playgroud)

人们期望在控制台中看到“Hello”,但我只在控制台中看到错误:

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

小智 5

请更换代码并检查

插件.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";
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    );
Run Code Online (Sandbox Code Playgroud)