首页 > 解决方案 > Wordpress 在使用 fetch API 的 ajax 调用上返回 400 Bad Request

问题描述

我正在使用 fetch API 语法对 admin-ajax.php 进行 Ajax 调用。下面是调用后端脚本的代码:

fetch(ajax_obj.ajaxurl, {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    body: JSON.stringify(this.data),
    headers: {
      "Content-Type": "application/json"
    }
  })

并得到 400 Bad Request 响应。

有人能告诉我这个要求哪里不对吗?

在chrome中检查网络开发工具时,我可以看到发送的正文是好的,url也是好的……据我所知,4xx状态码是客户端的错误,所以我甚至不看服务器端代码...如果我错了,请给我反馈...

实际上,我有这样的 jQuery ajax 调用:

this.data = {
              'action': 'ajax_product_query',
              'locations': this.locations,
              'type': this.category != '' ? this.category : [],
              'all-locations': this.filters['locationFilter'].all.checked,
              'page': ajax_obj.current_page
            };

          $.ajax({
            url: ajax_obj.ajaxurl,
            method: 'post',
            dataType: 'json',
            data: this.data,
            beforeSend: function(xhr) {
              button.innerHTML = 'Loading...';
            },
            success: (data) => {  ...

......它就像一个魅力......

比,愿意删除 jQuery 依赖,想要将 jQuery ajax 调用转换为 Fetch API 语法,如下所示:

fetch(ajax_obj.ajaxurl, {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    body: JSON.stringify(this.data),
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => response.json()) ...

然后请求变成了 400 个错误请求......

谢谢!

标签: ajaxwordpressfetch-api

解决方案


因为在 JS 获取 'POST' 请求后,您无法在 PHP 中获取 $_POST 数据。肮脏的解决方案。您可以在“/wp-admin/admin-ajax.php”中添加此代码来解决此问题:

if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
  $post = trim(file_get_contents("php://input"));
  $_POST = ( array ) json_decode( $post );
    $_REQUEST['action'] = $_POST['action'];
}

或者尝试找到更好的解决方案。
PS对不起我的英语


推荐阅读