实际上,作为我通过AJAX发送的对象,我的JSON数据是:
{
plotId: "668",
geogPhysZone: "4",
districtCode: "4",
posMethod: "1",
sRS: "45",
crewLeader: "",
date: "",
distanceToOtherLanduse: "",
distanceToSettlement: ""
}
但是,从JSON中传出
null
的值在发布时在我的表列中不可用,所以我得到500(内部服务器错误)。因此,在从AJAX发送时,我想忽略为空的值。单击按钮时将调用我的代码:
$("#generalSubmitButton").click(function(event) {
event.preventDefault();
var form_data = Object.assign($("#generalForm1").toObject(), $("#headForm").toObject());
console.log(form_data);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/form/api/plot-general/save",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(form_data),
success: function() {
alert("Successful");
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
});
最佳答案
您可以遍历对象,并消除没有价值的对象。
var myObject= {plotId: "668", geogPhysZone: "4", districtCode: "4", posMethod: "1", sRS: "45",crewLeader:"",date:"",distanceToOtherLanduse:"",distanceToSettlement:""};
Object.keys(myObject).forEach(function(key) {
var val = myObject[key];
if($.trim(val).length == 0){ //delete which are null or blank
delete myObject[key];
}
});
Demo
关于javascript - 通过AJAX发布时如何忽略JSON数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51184765/