简单的wordpress ajax查询无法正常工作

时间:2018-05-30 13:57:37

标签: ajax wordpress admin-ajax

你知道为什么这个简单的wp ajax查询不起作用吗?它总是返回失败。控制台 - > 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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

还有另一种选择。我同意塞缪尔,但我正在分享另一个选择

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' );

答案 2 :(得分:0)

你的行动是'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");
        }
    });
相关问题