The client collects form information.
Use the XMLHttpRequest object to submit to the server.
The server completes the verification logic and returns the result information.
The browser prompts the user based on the information returned by the server.
However, because my space does not support any server segment language, I moved the logic that should have been on the server to the browser, which is made by JavaScript. The server is only responsible for providing a list of user names. The final result is as follows. Try to enter the user names "test" and "cainiao8", and the user names "registered" will be displayed.
JavaScript code analysis
First, when the document is loaded, set the change Event Response Function ajaxValidate for the table. The Code is as follows:
Program code
AddEventSimple (window, 'load', function (){
Var test = document. getElementById ('username ');
AddEventSimple (test, 'change', ajaxValidate );
}
In this way, when the value in the User Name text box changes, the ajaxValidate function is called. The Code is as follows:
Program code
Function ajaxValidate (){
Var options = {
Url: 'ajax/ajaxUsernames. xml ',
Listener: callback,
Method: 'get'
}
Var request = createRequest (options );
Request. send (null );
}
It uses the previously introduced createRequest function to initialize an XMLHttpRequest object and sends it to the server to request the ajaxUsernames. xml file.
Finally, the callback function is used:
Program code
Copy codeThe Code is as follows:
Function callback (){
Var xmlDoc = this. responseXML;
Var root = xmlDoc. getElementsByTagName ('root') [0];
Var nodes = root. getElementsByTagName ("username ");
Var currentNode = null;
Var username = document. getElementById ('username'). value;
For (var I = 0; I <nodes. length; I ++ ){
CurrentNode = nodes [I];
If (username = currentNode. childNodes [0]. nodeValue ){
Document. getElementById ('test'). innerHTML = 'sorry! '+ Username +' has been registered. ';
Return;
}
}
Document. getElementById ('test'). innerHTML = 'username' + username + 'can be used! ';
}
The callback function searches for existing user names and determines whether the user already exists.