通过AJAX发布时如何忽略JSON数据?

时间:2018-07-05 06:38:15

标签: javascript jquery json ajax

实际上,作为我通过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");
      }
    }
  });
});    

1 个答案:

答案 0 :(得分:1)

您可以遍历对象并消除没有价值的对象。

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