ajax在wordpress中发送400错误请求错误

时间:2018-02-08 16:02:06

标签: javascript php jquery ajax wordpress

大家好我想在wordpress中使用ajax并陷入困境。我的代码在控制台中给我一个错误

    jquery-3.3.1.js:9600 GET http://localhost/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
(anonymous) @ main.js?ver=1:27
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991

我查看了源代码,它向我显示了此行的错误

xhr.send( options.hasContent && options.data || null );

这是我的jquery

$('#retrieve_users').click(function() {

    $.ajax({
            type: "GET",
            url: scriptData.ajaxurl,
            action : 'retrieveUsersData',
            dataType: "html",   //expect html to be returned                
            success: function(response)
            {                    
                $("#users_data").html(response); 
                //alert(response);
            }
        });
});

这是我在functions.php文件中的php代码

function retrieveUsersData(){

echo "ajax responding";
}

add_action('wp_ajax_retrieveUsersData','retrieveUsersData');
add_action('wp_ajax_nopriv_retrieveUsersData', 'retrieveUsersData');

这是我的HTML

<button id="retrieve_users">Watch Users</button>
                <div id="users_data"></div>

请帮忙!!我不知道如何使用wp_enque_scripts在wordpress中导入jquery src链接,所以我直接在html中粘贴了jquery src。我希望它不会造成问题

请帮助..我真的很感激。谢谢

1 个答案:

答案 0 :(得分:3)

将您的代码更改为使用POST,并在请求正文中使用操作键:

jQuery.ajax({
            url: scriptData.ajaxurl,
            type: "POST",
            dataType: 'html',
            data: {
                action: 'retrieveUsersData'
            },

            ...
});

此外,您应该在函数中使用die()来阻止0被回显。

function retrieveUsersData(){
    echo "ajax responding";
    die();
}
相关问题