Using the XMLHttpRequest object is divided into four steps:
1. Create the XMLHttpRequest component
2. Set the callback function
3. Initialize the XMLHttpRequest component
4. Send the request
Example code:
var userName;
var passWord;
var xmlHttpRequest;
//XmlHttpRequest object
function createXmlHttpRequest(){
if(window.ActiveXObject){ //If it is IE browser
return new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){ //Non-IE browsers
return new XMLHttpRequest();
}
}
function onLogin(){
userName = document.f1.username.value ;
passWord = document.f1.password.value;
var url = "LoginServlet?username=" userName "&password=" passWord "";
//1. Create XMLHttpRequest component
xmlHttpRequest = createXmlHttpRequest();
//2. Set the callback function
xmlHttpRequest.onreadystatechange = zswFun;
//3. Initialize the XMLHttpRequest component
xmlHttpRequest.open("POST",url,true);
//4. Send request
xmlHttpRequest.send(null);
}
//Callback function
function zswFun(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest .status == 200){
var b = xmlHttpRequest.responseText;
if(b == "true"){
alert("Login successful! ");
}else{
alert("Login failed!");
}
}
}