[英]Why is this ajax call being made even though it shouldn't be
我有這個驗證腳本即時通訊正在工作,但看不到為什么即時通訊有問題。
您可以看到我有一個check = false / true,請在運行ajax調用之前進行檢查。
但是,即使一個字段為空並且check設置為false,它仍在運行該調用。
所以:
// JavaScript - Update Password AJAX
$(document).ready(function () {
// When the form is submitted
$('.updatepasswordform').submit(function () {
var check = true;
// Get the values
var password1 = $("input[name=password1]").val();
var password2 = $("input[name=password2]").val();
var newpassword = $("input[name=newpassword]").val();
/* Password Validation */
// If fields are empty
if (password1 === '') {
check = false;
$("input[name=password1]").css('border', 'solid 2px red');
}
// If fields are empty
if (password2 === '') {
check = false;
$("input[name=password2]").css('border', 'solid 2px red');
}
// If fields are empty
if (newpassword === '') {
check = false;
$("input[name=newpassword]").css('border', 'solid 2px red');
}
if (check = true) {
$.ajax({
type: "POST",
url: "process/updatepassword.php",
data: $(".updatepasswordform").serialize(),
dataType: "json",
success: function (response) {
/* Checks for database validation, removed for space saving */
}
});
}
return false;
});
});
if (check = true)
是分配。 您需要檢查。
if (check == true) {
或者就像JasonP提到的那樣
if (check) {
您在if語句中僅使用一個等於。 改成這個
if (check == true) {
甚至更好
if (check) {
您使用賦值=
而不是比較==
來測試check
。 代替這個...
if (check = true) {
你的意思是這樣寫:
if (check == true) {
這是一個常見的陷阱。 將true
賦值以check
if
語句的條件是完全有效的,盡管在這種情況下,這不是您的本意。 check = true
的結果也為 true
(允許並行分配, a = b = c = true
可以工作),因此從本質上講,您在執行if (true)
。 這是可取的,盡管經常不小心使用會引起麻煩。 一般用途是將表達式的結果分配給范圍為if
語句的臨時變量。
基本上,代替這個...
var result = expensiveCalculation()
if (result) {
// do something with result
}
...它可以讓你這樣寫:
if (result = expensiveCalculation()) {
// do something with result
}
注意:
在這種特殊情況下,當您針對布爾值true
/ false
進行測試時,始終最好只編寫if (check)
或if (!check)
而不是使用==
進行顯式比較。
筆記2:
“ check”是一個特別糟糕的變量名。 您的變量應富有表現力; 我應該知道它的作用,無需評論。 在這種情況下,我會至少稱它為valid
,或者可能是formIsValid
,或者將檢查結果反轉並使用var errors = false
和if (!errors)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.