[英]typeof isn't working as expected with ajax response
我正在嘗試使用 AJAX 和 PHP 創建簡單的表單驗證,但typeof
的使用沒有按預期工作。
它運行良好,除非我得到一個空響應,這意味着所有字段都已通過驗證。
在這種情況下,什么都不會發生,最后一個輸入仍然保留其錯誤類,並且 Cart div
沒有按照成功請求的預期更改為 Success 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" });
}
}
});
有沒有更好的方法來做到這一點?
也許你可以檢查一下(除非我誤解了邏輯):
// 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.