To do a form validation inside the simplest example, check the existence of the user name, using AJAX to complete the form verification of the normal steps should be:
The client collects the form information.
Submit to the server using the XMLHttpRequest object.
The server completes the validation logic and returns the result information.
The browser side makes certain prompts to the user based on the information returned by the server.
However, since my space does not support any Server segment language, the logic that should be in the server is moved to the browser, made by JavaScript, and the server is only responsible for providing a list of user names. The final effect is as follows, try to enter Test,cainiao8 these username, will show registered.
JavaScript code Analysis
First, when the document is loaded, the response function to set the Change event for the table is ajaxvalidate and the code is as follows:
addEventSimple(window,'load',function(){
var test = document.getElementById('username');
addEventSimple(test,'change',ajaxValidate);});
This way, when the value in the User Name text box changes, the Ajaxvalidate function is invoked with the following code:
function ajaxValidate(){
var options = {
url:'ajax/ajaxUsernames.xml',
listener:callback,
method:'GET'
}
var request = createRequest(options);
request.send(null);
}
It initializes a XMLHttpRequest object using the Createrequest function described earlier and sends it to the server, requesting ajaxusernames.xml files.
The last is the callback function:
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
= '对不起!'+username+'已经被注册。';
return;
}
}
document.getElementById('test').innerHTML = '用户名' + username +'可以使用!';
}
The callback function searches for the name of the current user input in the existing user name to determine if it already exists.