javascript - $.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 对此发表评论
解决方案
您的 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);
}
});
推荐阅读
- javascript - plotly javascript scatter更新数据
- javascript - 在鼠标悬停期间替换部分 URL 以获得原始大小的图像
- r - 如何使用 R 从共享点文件夹下载文件
- bash - Add multiple commands in single alias
- mysql - 如何创建 API 以在 MySQL 中插入数据,并使用重复键传递 json
- postgresql - PostgreSQL 语法错误我不明白
- javascript - 如何设置条件来比较 if 语句中的变量值?
- mysql - SQL- Add up all the values in a resulting column and calculate the percentage using another column in the same query
- php - 将产品标签移至 WooCommerce 产品描述
- octobercms - 十月CMS | 如何在 OctoberCMS 中启用目录以供下载?