本文介绍了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
},

这篇关于Wordpress admin-ajax.php 400错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:58