Home >Web Front-end >JS Tutorial >A brief analysis of the invalid problem of using ajax's return false when onsubmit is validating the form_jquery

A brief analysis of the invalid problem of using ajax's return false when onsubmit is validating the form_jquery

WBOY
WBOYOriginal
2016-05-16 17:29:211007browse
Copy code The code is as follows:

/**
* Form submission verification
**/
function onSubmit() {
if($('#name').val().length<2){
alert("The name must be no less than 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.");
                                                                                                                          ; Reasons:


1. The function that returns false during ajax is not the same function as onsubmit();
2. When ajax is executed, the default setting value of async is true. In this case, Asynchronous mode means that after ajax sends a request, while waiting for the server to return, the front desk will continue to execute the script behind the ajax block. Success will not be executed until the server returns the correct result, which means that it is executed at this time. The are two threads, one thread after the ajax block makes the request and the script after the ajax block (another thread).

Modified code:

Copy code

The code is as follows:
/** * Form submission verification **/function onSubmit(){ if($('#name').val().length<2){ alert("name Please no less than two Chinese characters");                                                                                                                                                                                                                                                         {
type: "POST",
async:false, // Set synchronization method
cache:false,
url: "/users/checkrepeat/",
data: "name= " $('#name').val() "&time=" t,
success:function(res){
if(res == 'exists'){
alert("Name already exists Please modify. ");
FLAG = FALSE;
}
}
});
if (! Flag)
Return false;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn