首页 > 解决方案 > $.ajax 在尝试发送长 JSON 时返回“错误”

问题描述

我在 JS 中生成对象数组,然后使用$.ajax (using 'JSON.stringify(myData)').
当该数组内部有 50 个对象(JSON.length == 2401)时,它工作正常,但如果数组有 77 个对象(JSON.length == 3709),它会返回“错误”

对象结构:

{ user_id: "27", hours: "2", service_id: "561" }

为什么会发生这种“错误”?

当我尝试发送那个长 JSON 时,我在没有任何数据的域日志中得到带有“000”代码的“访问”条目。
JSON字符串有效,用在线json解码器检查。

发送 AJAX 的代码:

requestReport() {
    this.makeObjectForAjax();
    const requestString = this.entriesForAjax;
    const auth = $('#auth').text();
    console.log(requestString);
    $.ajax({
        url: "/bitrix/TimeSheet/generateReport.php",
        data: {
            'data' : requestString,
            'auth' : auth
        },
        success: function (data, textStatus) {
            console.log(data);
            console.log(textStatus);
        },
        error: function (data, textStatus, thrown) {
            console.log(data);
            console.log(textStatus);
            console.log(thrown);
        }
    });
}

所以$.ajax执行 'error: function', 'textStatus' == 'error', 'throw' is empty string

该方法首先从 JS 获取的原始数据生成一个数组,然后生成 JSON

makeObjectForAjax() {
    let entriesArray = [];
    this.rawEntries.forEach(function (record) {
        let newObj = {
            'user_id' : Object.values(record.PROPERTY_117)[0],
            'hours' : Object.values(record.PROPERTY_119)[0],
            'service_id' : Object.values(record.PROPERTY_275)[0],
        };
        entriesArray.push(newObj);
    });
    this.entriesForAjax = JSON.stringify(entriesArray);
}

console.log(entriesArray) 显示对象数组是有效的
在线 JSON 解码器说该字符串来自

this.entriesForAjax = JSON.stringify(entriesArray);

也有效

UPD:解决了!问题是$.ajax默认情况下会发出 GET 请求。添加type: 'POST'到它,现在它可以工作了!
感谢@Phil 对此发表评论

标签: javascriptjqueryjsonajax

解决方案


您的 dataType: "json" 仅告诉 jQuery 您希望它解析返回的 JSON,并不意味着 jQuery 会自动对您的请求数据进行字符串化。

$.ajax({
        type: "POST",
        url : "URL",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            user_id: 27,
            hours: 2,
            service_id: 561,
        }),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
});

推荐阅读