Wordpress admin-ajax.php 400 错误请求

问题描述:

我对 wordpress admin-ajax.php 文件有一个奇怪且令人沮丧的行为,当我发出 ajax 请求时,它返回 400 错误错误请求.

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.

(function( $ ) {
    var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
    $.ajax({
        url : ajaxscript.ajax_url,
        data : {
            action : 'cart_clb',
            id : 1
        },
        method : 'POST',
        success : function( response ){ console.log(response) },
        error : function(error){ console.log(error) }
    })
})(jQuery)

在我的functions.php中

And inside my functions.php

add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );

function cart_clb(){
    echo json_encode($_POST);
    die();
}

如上所述,当我执行请求时:

As said above when i execute the request :

mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

有人可以帮我取悦吗?谢谢.

Someone could help me to please? thank you.

首先,使用完整和绝对 url,使用协议(或至少与协议无关的形式):

First, use full and absolute url, with protocol (or at least protocol-independent form):

var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' } 

第二,你的ajax动作名不是php回调函数名,而是钩子的动态部分wp_ajax_{action_name}/wp_ajax_nopriv_{action_name},所以在你的情况下应该是:>

Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:

data : {
    action : 'post_cart_clb',
    id : 1
},