typeof在ajax响应中无法正常工作。

问题描述 投票:0回答:1

我试图用AJAX和PHP创建简单的表单验证,但使用的是 typeof 没有达到预期的效果。

除非我得到一个空的响应,这意味着所有的字段都通过了验证,否则它工作得很好。

在这种情况下,什么都不会发生,最后一个输入仍然是错误类和Cart div 是不会改变到成功 div 在请求成功后,如预期的那样。

一个典型的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" });
    }
  }
});

有什么更好的方法吗?

javascript ajax
1个回答
0
投票

也许你可以检查一下(除非我误解了逻辑)。

// If data.last_name is defined and has some value show error message, else remove it
if(data['last_name']) {
 l_name.addClass("error");
 $('#l_name-err').show();
} else {
  l_name.removeClass("error");
  $('#l_name-err').hide();
}

另外,typeof的写法不应该是你让它去掉"() "的方式。应该是这样的。typeof data['np_branch'] !== "undefined" 而不是 typeof(data['np_branch']) != "undefined"

© www.soinside.com 2019 - 2024. All rights reserved.