简单的 wordpress ajax 查询不起作用

Simple wordpress ajax query is not working

您知道为什么这个简单的 wp ajax 查询不起作用吗?它总是 returns 失败。控制台 -> https://pastebin.com/TABQCjXe

jQuery(document).ready(function($) {

// This does the ajax request
$.ajax({
    type: 'post',
    url: ajaxurl,
    data: {
        'action':'prefix_load_cat_posts'
    },
    success:function(data) {
        // This outputs the result of the ajax request
        console.log(data);
        $( ".prefix_load_cat_posts" ).append("success");
    },
    error: function(errorThrown){
        console.log(errorThrown);
        $( ".prefix_load_cat_posts" ).append("fail");
    }
});

});

PHP -> https://pastebin.com/g4QiWDky

操作应该是 load-filter 而不是 prefix_load_cat_posts。看到你的PHP代码,prefix_load_cat_posts实际上是回调函数名。

data: {
    'action':'load-filter'
},

你的动作是 'load_filter',你也必须本地化 ajaxurl 使用这个函数 wp_localize_script

$.ajax({
        type: 'post',
        url: ajaxurl,
        data: {
            'action':'load-filter'
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
            $( ".prefix_load_cat_posts" ).append("success");
        },
        error: function(errorThrown){
            console.log(errorThrown);
            $( ".prefix_load_cat_posts" ).append("fail");
        }
    });

还有另一种选择。我同意塞缪尔的观点,但我分享了另一种选择

add_action( 'wp_ajax_nopriv_prefix_load_cat_posts', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_prefix_load_cat_posts', 'prefix_load_cat_posts' );