ajax在wordpress中发送400错误请求错误 [英] ajax sending 400 bad request error in wordpress

查看:85
本文介绍了ajax在wordpress中发送400错误请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我试图在Wordpress中使用Ajax并卡在某些东西中.我的代码使控制台出现错误

Hi everyone i am trying to use ajax in wordpress and got stuck in something. My code is giving me an error in console as

    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

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

I looked into the source and it is showing me the error on this line

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

这是我的jQuery

This is my 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代码

This is my php code in functions.php file

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链接,所以我直接将jQuery src粘贴到html中.我希望它不会造成问题

Please help!! I didnt know how to import jquery src link in wordpress using wp_enque_scripts so i pasted the with jquery src directly in html. I hope its not creating problem

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

Please help.. i would really appreciate it. Thank you

推荐答案

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

Change your code to use POST and in the body of the request use the action key :

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

            ...
});

还应该在函数中使用die(),以防止回显0.

Also you should use die() in the function to prevent the 0 to be echoed.

function retrieveUsersData(){
    echo "ajax responding";
    die();
}

这篇关于ajax在wordpress中发送400错误请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆