Copy Code code as follows:
/**
* Form submission Verification
**/
function OnSubmit () {
if ($ (' #name '). Val (). length<2) {
Alert ("Name please not less than two 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 ("Name already exists, please modify.");
return false;
}
}
});
}
Problem Reason:
1. The function of return false in Ajax is not the same as onsubmit ();
2. In the case of Ajax execution, the default setting value of Async is true, which is asynchronous, that is, when Ajax sends a request, the foreground will continue to execute the script behind the AJAX block while the server is waiting for it to return. It is not until the server side returns the correct results that the success is executed, that is, two threads are executed at this time, and the Ajax block makes the script (another thread) after the request followed by a thread and an AJAX block.
Modified code:
Copy Code code as follows:
/**
* Form submission Verification
**/
function OnSubmit () {
if ($ (' #name '). Val (). length<2) {
Alert ("Name please not less than two characters");
return false;
}
var flag = true;
var t = new Date (). GetTime ();
$.ajax ({
Type: "POST",
Async:false,//Set sync mode
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;