我正在使用JSON stringify转换复杂对象。
我想要这种输出,以便可以轻松地将其与模型绑定。
DateRequired: "2019-02-02"
DeliveryDestination: "test"
ProjectCode: "002P"
RequestItems: {InventoryItemsId: "2", Brand: "NIKE", Types: "Casual", Specification: "Mentality", ItemName: "Wild"},
{InventoryItemsId: "3", Brand: "PUMA", Types: "Running", Specification: "Energy", ItemName: "Wild"}
但是我得到了这个。
DateRequired: "2019-02-02"
DeliveryDestination: "test"
ProjectCode: "002P"
RequestItems: Array(2)
0: {InventoryItemsId: "2", Brand: "NIKE", Types: "Casual", Specification: "Mentality", ItemName: "Wild", …}
1: {InventoryItemsId: "3", Brand: "PUMA", Types: "Running", Specification: "Energy", ItemName: "Wild", …}
length: 2
__proto__: Array(0)
__proto__: Object
这是发布数据的代码:
var items = postAllItems(); //this is an array
var materialRequest = {
'DateRequired': $('#txtDateRequired').val(),
'ProjectCode': $('#txtProjectCode').val(),
'DeliveryDestination': $('#txtDeliveryDestination').val(),
'RequestItems': items
};
postMaterialRequest(materialRequest);
function postMaterialRequest(materials) {
$.ajax({
contentType: 'application/json',
type: 'POST',
url: '/api/PostMaterial',
data: JSON.stringify(materials),
success: function (data) {
console.log("Info Save " + data);
},
failure: function (response) {
console.log('Failed to save.');
}
});
}
这就是我从Web API所获得的
答案 0 :(得分:1)
是正确的输出-这只是控制台显示对象的方式。使用StackOverflow的控制台或使用JSON.stringify
,可以显示所需的输出:
var myObj = {
DateRequired: "2019-02-02",
DeliveryDestination: "test",
ProjectCode: "002P",
RequestItems: [{
InventoryItemsId: "2",
Brand: "NIKE",
Types: "Casual",
Specification: "Mentality",
ItemName: "Wild"
},
{
InventoryItemsId: "3",
Brand: "PUMA",
Types: "Running",
Specification: "Energy",
ItemName: "Wild"
}
]
};
console.log(myObj);
console.log(JSON.stringify(myObj));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
我通过使用下面的代码解决了我的问题,我的问题全部是关于不将同步与异步功能混合在一起。其中ajax发布首先完成。我用setTimeout来延迟ajax发布。感谢@trincot链接。
function createObject() {
var mr = { DateRequired: $('#txtDateRequired').val(), ProjectCode: $('#txtProjectCode').val(), DeliveryDestination: $('#txtDeliveryDestination').val(), RequestItems: [] };
for (var i = 0; i < insMaterials.length; i++) {
var mtr = insMaterials[i];
alert(mtr);
var RequestItems = {
'InventoryItemsId': mtr.InventoryItemsId,
'Brand': mtr.Brand,
'ItemName': mtr.ItemName,
'Quantity': mtr.qty,
'RefNo': 3,
'Comment': mtr.remarks,
'Specification': mtr.specification,
'Types': mtr.types,
'Unit': mtr.qty
};
mr.RequestItems.push(RequestItems);
}
return JSON.stringify(mr);
}
function postMaterialRequest() {
$.ajax({
contentType: 'application/json',
async: false,
type: 'POST',
url: '/api/PostMaterial',
data: (createObject()),
success: function (data) {
console.log("Info Save " + data);
toastr.success('Request was submitted successfully!');
del();
},
failure: function (response) {
console.log('Failed to save.');
toastr.error('Failed to save.');
}
});
}
postAllItems();
setTimeout(postMaterialRequest, 3000);