//当页面加载完毕之后加载此页面
var xmlRequest; //全局变量的定义
function createXMLHttpRequest() {
alert("createXMLHttpRequest");
var xmlRequest;
//创建XMLHttpRequest对象
try{
xmlRequest=new XMLHttpRequest(); //按照web标准来创建XMLhttpRequest对象,非IE浏览器
}catch(e){
try{//Msxml2.XMLHTTP
xmlRequest=new ActiveXObject("Msxml2.XMLHTTP"); //按照微软的方式来创建,IE6及以上版本皆可以
}catch(e){
xmlRequest=new ActiveXObject("Microsoft.XMLHTTP"); //所有IE浏览器均可用,但是性能没有上一个好
}//Microsoft.XMLHttp
}
//返回xmlRequest对象
return xmlRequest;
}
//老方法获取XMLHttpRequest对象
function getXMLHttpRequest(){
var xmlRequest=null; //
if(window.XMLRequest){ //非IE浏览器
xmlRequest=new XMLHttpRequest();
}else{
xmlRequest=new ActiveObject("Microsoft.XMLHTTP"); //IE浏览器
}
return xmlRequest;
}
//加载方法:
window.onload=function(){
alert("has loaded...");
document.getElementById("ok").onclick=function(){
//创建XMLHttpRequest对象
var xmlRequest=createXMLHttpRequest();
/*
* 服务器向浏览器请求响应
* readyState
* 0 代表未初始化。 还没有调用 open 方法
1 代表正在加载。 open 方法已被调用,但 send 方法还没有被调用
2 代表已加载完毕。send 已被调用。请求已经开始
3 代表交互中。服务器正在发送响应
4 代表完成。响应发送完毕
*/
xmlRequest.onreadystatechange=function(){
alert(xmlRequest.readystate);
if(xmlRequest.readystate==4){
if(xmlRequest.status==400||xmlRequest.status==304){
var data=xmlRequest.responseText;
alert(data);
}
}
}
/*
* 浏览器与服务器建立连接
*/
xmlRequest.open("GET","../servlet/getservlet",true);
//alert("../servlet/getservlet");
/*
* 浏览器向服务器发送请求,send方法
*/
xmlRequest.send("a=3&b=3");
}
}
原文:http://my.oschina.net/u/1765238/blog/293657