以下代码块打算从Datatable收集名为materialsInMaterialsRecieved的数据和一个名为materials-recieved的表单,并创建一个如下所示的对象.
{
PurchaSEOrderId: "1",ReceivedDate: "07/23/2016",MaterialsInMaterialsRecived: {
Cost: "2",MaterialId: "1",MaterialName: "Silk",QuantityDispatched: "2",QuantityRecieved: "2",Remark: "asda"
}
}
正在创建此对象并将其存储为submitData. submitData需要通过ajax发送到API网址.但是当这样做时,会抛出一个错误,表示Uncaught RangeError:超出了最大调用堆栈大小.
以下是html标记,
SEOrderId" class="form-control" id="PurchaSEOrderList">
以下是javacript代码,
$("#create-materials-recieved-note").on('click',function (event) {
var submitData = {};
var materials = materialsInMaterialsRecieved.rows().data(); // materialsInMaterialsRecieved is a handle for a Datatable
$("#materials-recieved .form-control").each(function () {
submitData[$(this).attr2("name")] = $(this).val();
})
submitData["MaterialsInMaterialsRecived"] = materials;
console.log(submitData);
$.ajax({
type: 'post',// define the type of http verb we want to use (post for our form)
url: '/api/MaterialsRecieveds/AddMaterialsRecieved',// the url where we want to post
data: submitData,// our data object
dataType: 'json',// what type of data do we expect back from the server
contentType: 'application/json',success: function (data) {
console.log(data);
}
});
event.preventDefault();
});
如果我注释掉$.ajax(…语句,那么错误就不会出现.
最佳答案
submitData是一个巨大的类数组对象.如果我将submitData直接传递给$.ajax,JQuery会尝试将有效负载数据序列化为json,因为我已经将dataType作为’json’.这个JQuery序列化创建了许多方法回调并冻结了浏览器,然后抛出错误通知它.
解决此问题的简单方法是避免JQuery序列化并将字符串化版本的有效负载数据传递给ajax调用.
$.ajax({
type: 'post',url: '/api/MaterialsRecieveds/AddMaterialsRecieved',data: JSON.stringify(submitData),// stringyfy before passing
dataType: 'json',// payload is json
contentType : 'application/json',success: function (data) {
console.log(data);
}
});