Analysis on the problem that ajax return false is used to verify an onsubmit form is invalid

Source: Internet
Author: User

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.