使用ajax响应,typeof无法正常工作

I'm trying to create simple form validation with AJAX and PHP but the usage of typeof is not working as expected.

除非我收到一个空响应,这意味着所有字段均已通过验证,否则它会很好地工作。

In that case, nothing happens and the last input remains with its error classes and Cart div is not changing to the Success div as intended upon a successful request.

JSON中的典型响应:

{
  last_name: "The Last name is required", 
  email: "The Email is required", 
  city: "The City is required", 
  np_branch: "The Np branch is required"
}

显然,如果其中一个值通过了PHP验证,则不会将其添加到数组中。请注意,每个键的错误值可能会根据错误而变化,因此,检查错误消息不是一种选择。

码:

$.ajax({
  type: "POST",
  dataType:"json",
  data: {
    last_name: l_name.val(),
    email: email.val(),
    city: city.val(),
    np_branch: np_branch.val()
  },
  success: function(data) {
    console.log(data);
    // If all fields passed validation we hide the Cart div and show the Success div
    if (typeof(data['last_name']) == "undefined" && typeof(data['email']) == "undefined" && typeof(data['city']) == "undefined" && typeof(data['np_branch']) == "undefined") {
      $('.cart').css({ "display":"none" });
      $('.success').css({ "display":"block" });
    }
    // Checking whether the response contains a last_name error
    if (typeof(data['last_name']) != "undefined" && data['last_name'] !== null) {
      l_name.addClass("error");
      $('#l_name-err').css({ "display":"block" });
    } else if (l_name.hasClass('error')) {
      l_name.removeClass("error");
      $('#l_name-err').css({ "display":"none" });
    }
    // Checking whether the response contains a email error
    if (typeof(data['email']) != "undefined" && data['email'] !== null) {
      email.addClass("error");
      $('#email-err').css({ "display":"block" });
    } else if (email.hasClass('error')) {
      email.removeClass("error");
      $('#email-err').css({ "display":"none" });
    }
    // Checking whether the response contains a city error
    if (typeof(data['city']) != "undefined" && data['city'] !== null) {
      city.addClass("error");
      $('#city-err').css({ "display":"block" });
    } else if (city.hasClass('error')) {
      city.removeClass("error");
      $('#city-err').css({ "display":"none" });
    }
    // Checking whether the response contains a np_branch error
    if (typeof(data['np_branch']) != "undefined" && data['np_branch'] !== null) {
      np_branch.addClass("error");
      $('#branch-err').css({ "display":"block" });
    } else if (np_branch.hasClass('error')) {
      np_branch.removeClass("error");
      $('#branch-err').css({ "display":"none" });
    }
  }
});

有更好的方法吗?