Copy codeThe Code is as follows:
/**
* Form submission Verification
**/
Function onSubmit (){
If ($ ('# name'). val (). length <2 ){
Alert ("the name must be at least two Chinese characters ");
Return false;
}
Var t = new Date (). getTime ();
$. Ajax ({
Type: "POST ",
Url: "/users/checkrepeat /",
Data: "name =" + $ ('# name'). val () + "& time =" + t,
Success: function (res ){
If (res = 'exists '){
Alert ("the name already exists. Please modify it .");
Return false;
}
}
});
}
Cause:
1. The function with return false in ajax is not the same as onsubmit;
2. when ajax is executed, the default value of async is true, which is asynchronous, that is, when ajax sends a request, it is waiting for the server to return this process, the foreground will continue to execute the script after the ajax block until the server returns the correct result to execute success. That is to say, two threads are executed at this time, the second thread after the ajax block sends the request and the script after the ajax block (another thread ).
Modified code:
Copy codeThe Code is as follows:
/**
* Form submission Verification
**/
Function onSubmit (){
If ($ ('# name'). val (). length <2 ){
Alert ("the name must be at least two Chinese characters ");
Return false;
}
Var flag = true;
Var t = new Date (). getTime ();
$. Ajax ({
Type: "POST ",
Async: false, // set the synchronization mode
Cache: false,
Url: "/users/checkrepeat /",
Data: "name =" + $ ('# name'). val () + "& time =" + t,
Success: function (res ){
If (res = 'exists '){
Alert ("the name already exists. Please modify it .");
Flag = false;
}
}
});
If (! Flag)
Return false;