您的位置:首页 > Web前端 > JavaScript

JavaScript下通过的XMLHttpRequest发送请求的代码

2011-06-28 00:00 741 查看
使用XMLHttpRequest对象分为4部完成:
1.创建XMLHttpRequest组建
2.设置回调函数
3.初始化XMLHttpRequest组建
4.发送请求
实例代码:
var userName; 
var passWord; 
var xmlHttpRequest; 
//XmlHttpRequest对象 
function createXmlHttpRequest(){ 
if(window.ActiveXObject){ //如果是IE浏览器 
return new ActiveXObject("Microsoft.XMLHTTP"); 
}else if(window.XMLHttpRequest){ //非IE浏览器 
return new XMLHttpRequest(); 
} 
} 
function onLogin(){ 
userName = document.f1.username.value; 
passWord = document.f1.password.value; 
var url = "LoginServlet?username="+userName+"&password="+passWord+""; 
//1.创建XMLHttpRequest组建 
xmlHttpRequest = createXmlHttpRequest(); 
//2.设置回调函数 
xmlHttpRequest.onreadystatechange = zswFun; 
//3.初始化XMLHttpRequest组建 
xmlHttpRequest.open("POST",url,true); 
//4.发送请求 
xmlHttpRequest.send(null); 
} 
//回调函数 
function zswFun(){ 
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){ 
var b = xmlHttpRequest.responseText; 
if(b == "true"){ 
alert("登录成功!"); 
}else{ 
alert("登录失败!"); 
} 
} 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: