为什么我会收到状态码:WP Ajax出现400错误的请求错误? [英] Why am I getting a Status Code: 400 Bad Request error with WP Ajax?

查看:65
本文介绍了为什么我会收到状态码:WP Ajax出现400错误的请求错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对这个问题进行了数小时的排查,对于为什么会发生此错误感到困惑.

I have been troubleshooting this for hours now and I am stumped as to why this error is occurring.

在我的JS中,我有以下ajax:

in my JS I have the following ajax:

var $ = jQuery; // define jquery
let name = "Mark";
let pies = "cherry";

$(document).ready(function(){
    $.ajax({
        type : 'POST',
        dataType : 'json',
        url : ajaxurl,
        nonce: nonce,
        data : {
            action: 'myfunction',
            name: name,
            pies: pies,
            nonce: nonce
        }
    }).done(function(response) {
        console.log(response);
    });
}); // end document ready

在我插件的PHP中,

    function myfunction() {    
        if ( wp_verify_nonce( $_POST['nonce'], 'registration_nonce')) {
            $name = $_POST['name'];
            $pies = $_POST['pies'];
            file_put_contents('debug_output.txt', $pies);
            die();
        }
    }
    add_action( 'wp_ajax_myfunction', 'myfunction' );
    add_action( 'wp_ajax_nopriv_myfunction', 'myfunction');

这每次给我400.这应该是一件简单的事情,我通常会一直这样做,但是由于某种原因,我严重错过了一些东西.有任何想法吗?我把它缩小到最低限度,仍然没有运气.ajax URL和nonce都可以.WP中的某些内容有变化吗?

This gives me a 400 every single time. This should be a simple thing and I normally do this all of the time but for some reason, I am seriously missing something. Any ideas anyone? I whittled it done to the bare minimum and still no luck. Both the ajax URL and nonce are fine. Did something in WP change?

推荐答案

有些事情您可能应该修复/检查:

There are some things that maybe you should fix/check:

  1. 在您的PHP操作中以echo json_encode($ myDataArray)结尾,其中$ myDataArray类似于array("key" =>"value")ecc..
  2. 您在PHP动作内的最后一个函数调用应始终为"die"(死).或退出";或者只是使用WP wp_send_json();(您可以选择成功/失败的方法)
  3. 再次检查ajaxurl实际上是否指向admin_url('admin-ajax.php')
  4. 仔细检查您的add_action挂钩在AJAX调用实际发生之前在页面中的某处被调用

这篇关于为什么我会收到状态码:WP Ajax出现400错误的请求错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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