You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置contentType为application/json时Ajax请求失败,移除后PHP解析JSON出错

解决Ajax发送JSON时的contentType与PHP解析问题

我来帮你梳理下这个问题的根源,以及对应的解决办法:

为什么设置contentType: "application/json;charset=utf-8"会失败?

当你把contentType设为application/json时,jQuery会把你传入的data对象序列化成JSON字符串发送给后端,但PHP默认不会自动解析application/json格式的请求体——它只会自动处理application/x-www-form-urlencoded或multipart/form-data这两种格式的POST数据,所以你后端用$_POST['jsonitem']根本拿不到任何数据,自然会导致请求失败,前端收到"failed func"。

为什么移除contentType后PHP解析JSON报错?

不设置contentType时,jQuery默认用application/x-www-form-urlencoded格式发送数据,这时候它会对data里的每个参数做URL编码。你提前用JSON.stringify(json)把对象转成了字符串,这个字符串里的双引号会被自动转义成\",后端拿到的$jsonitem就是"{\"test\":\"testv\"}"(带多余转义的字符串),直接用json_decode解析的话,这些转义字符会导致语法错误。


两种可行的解决方案

方案1:保持默认contentType(推荐)

不需要提前stringify你的JSON对象,直接把原始对象传入data,让jQuery帮你处理编码:

var json = { test: "testv" };
var data = { 
    action: 'ajax_load_article', 
    jsonitem: json, // 这里直接传对象,不用提前stringify
};
var options = {
    url: beloadmore.url,
    dataType: "json",
    // 移除contentType,使用默认的application/x-www-form-urlencoded
    type: "POST",
    data: data,
    success: function(res, status, xhr) {
        if (res.success) {
            console.log(res);
            $('.site').append(res.data);
        } else {
            console.log("failed func");
            console.log(res);
        }
    },
    error: function(xhr, status, error) {
        console.log(xhr.responseText);
        console.log(error);
    }
};
$.ajax(options);

后端PHP代码可以直接接收解析:

$jsonitem = $_POST['jsonitem'];
// 前端传的对象会被PHP解析为数组,可直接转为对象使用
$jsonitemdecoded = (object)$jsonitem;
var_dump($jsonitemdecoded);
echo json_last_error_msg();

方案2:正确使用application/json格式

如果一定要用application/json contentType,需要把整个请求数据转成JSON字符串,后端从请求体读取:

var json = { test: "testv" };
// 把整个请求数据打包成JSON字符串
var data = JSON.stringify({
    action: 'ajax_load_article', 
    jsonitem: json
});
var options = {
    url: beloadmore.url,
    dataType: "json",
    contentType: "application/json;charset=utf-8",
    type: "POST",
    data: data, // 直接传JSON字符串
    success: function(res, status, xhr) {
        if (res.success) {
            console.log(res);
            $('.site').append(res.data);
        } else {
            console.log("failed func");
            console.log(res);
        }
    },
    error: function(xhr, status, error) {
        console.log(xhr.responseText);
        console.log(error);
    }
};
$.ajax(options);

后端PHP需要从php://input读取请求体再解析:

// 读取完整的请求体内容
$requestBody = file_get_contents('php://input');
$data = json_decode($requestBody);
$jsonitem = $data->jsonitem;
// 此时$jsonitem已经是解析好的对象,无需再次解码
var_dump($jsonitem);
echo json_last_error_msg();

内容的提问来源于stack exchange,提问作者GSDa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:38:21