Home > Web Front-end > JS Tutorial > Code for sending requests through XMLHttpRequest under JavaScript_javascript skills

Code for sending requests through XMLHttpRequest under JavaScript_javascript skills

WBOY
Release: 2016-05-16 18:05:29
Original
1361 people have browsed it

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:

Copy code The code is as follows:

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!");
}
}
}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template