通过XMLHttpRequest对象来向服务器发送异步请求,从服务器获得数据,用JavaScript来操作DOM从而更新页面。
XMLHttpRequest对象是Ajax技术的核心。
一套可以在Javascript等脚本语言中通过http协议传送或接收XML及其他数据的一套API。
在做项目的过程中,搜索框的联想功能中用到了Ajax技术,因为当时这个联想功能是属于公共部分,一个人做好,其他系统直接用,而且自己当时没学习Ajax,所以就直接按着文档去实现。现在趁着总结,结合这个联想功能的js文件,来总结XMLHttpRequest的五步使用法。
/*1.针对不同浏览器创建XMLHttpRequest对象*/
if(window.XMLHttpRequest){
//alert("IE7,IE8,FireFox");
xmlhttp =new XMLHttpRequest();
//针对某些特定版本的mozillar浏览器的BUG进行修正
//具体来说:浏览器是通过MIME Type来决定什么内容用什么形式显示
//如果来自服务器的响应没有 XML mime-type 头部,则一些版本的 Mozilla 浏览器不能正常运行。
//对于这种情况,httpRequest.overrideMimeType('text/xml'); 语句将覆盖发送给服务器的头部,强制 text/xml 作为 mime-type。
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
//alert("IE6,IE5.5,IE5");
var activexName=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP","Miscrosoft XMLHTTP"];
for(var i=0;i<activexName.length;i++) {
try{
xmlhttp=new ActiveXObject(activexName[i]);
break;
}catch(e){
}
}
}
if(xmlhttp == undefined || xmlhttp == null){
alert("当前浏览器不支持创建XMLHttpRequest对象,请更换浏览器");
return;
}
/*2.在XMLHttpRequest对象上注册回调函数*/
xmlhttp.onreadystatechange=callback;
//XMLHttpRequest对象有readyState属性和onreadystatechange属性(函数),当readyState属性改变时,就会调用onreadystatechange
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
//当onreadystatechange触发时,就会调用callback函数
/*3.使用open方法设置和服务器端交互的基本信息*/
//GET方式交互
xmlhttp.open("GET","AJAX?name=" + userName,true);
//POST方式交互
xmlhttp.open("POST","AJAX",true);
//POST方式交互所需增加的代码
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
/*4.设置发送的数据,开始和服务器端交互 */
//GET方式
xmlhttp.send(null);
//POST方式
xmlhttp.send("name=" + userName);
/*5.更新界面*/
//在回调函数中判断交互是否结束,响应是否正确,并根据需要获取服务器返回的数据,并更新页面
function callback(){
//判断和服务器端的交互是否完成,还要判断服务器端是否正确返回了数据
if(xmlhttp.readyState == 4){
//表示和服务器端的交互已经完成
if(xmlhttp.status == 200){
//表示服务器的是响应代码是200,正确返回了数据
var message=xmlhttp.responseText;
//XML数据对应的DOM对象的接受方法
//使用的前提是,服务器端需要设置contenttype为text/xml
//记忆像div标签中填充文本内容的方法
var div=document.getElementById("message");
div.innerHTML=message;
}
}
//创建一个"类",这个"类"具有XMLHTTP属性
function CallBackObject()
{
this.XmlHttp = this.GetHttpObject();
}
// 通过原型设置这个类的其他属性:
//通过GetHTTPObject获得XMLHTTPRequest对象,此属性中封装的是第一步
CallBackObject.prototype.GetHttpObject = function()
{
var xmlhttp;
// if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
// try {
// xmlhttp = new XMLHttpRequest();
// } catch (e) {
// xmlhttp = false;
// }
// }
try{
//对于Firefox和Opera等浏览器
xmlhttp=new XMLHttpRequest();
//有此版本的Mozilla浏览器在处理服务器返回的包含XML mime-type头部信息内容时会出错。
//所以,为了确保返回内容是text/xml信息,需要包含下面的语句。
if(xmlhttp.overrideMimeType)
{
xmlhttp.overrideMimeType("text/xml");
}
}catch(e){ //对于IE浏览器
var activexName=new Array('Msxml2.XMLHTTP.7.0',
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Micrsoft.XMLHTTP');
var success=false;
for(var i=0;i<activexName.length && !success;i++){
try{
xmlhttp=new ActiveXObject(activexName[i]);
success=true;
break;
}catch(e){
}
}
if(!success){
alert('Unable to create XMLHttpRequest.');
}
}
return xmlhttp;
}
}
//DoCallBack封装第二步,第三和第四步
CallBackObject.prototype.DoCallBack = function(URL)
{
if( this.XmlHttp )
{
if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
{
var oThis = this;
this.XmlHttp.open('POST', URL);
this.XmlHttp.onreadystatechange = function(){ oThis.ReadyStateChange(); };
this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.XmlHttp.send(null);
}
}
}
CallBackObject.prototype.AbortCallBack = function()
{
if( this.XmlHttp )
this.XmlHttp.abort();
}
CallBackObject.prototype.OnLoading = function()
{
// Loading
}
CallBackObject.prototype.OnLoaded = function()
{
// Loaded
}
CallBackObject.prototype.OnInteractive = function()
{
// Interactive
}
CallBackObject.prototype.OnComplete = function(responseText, responseXml)
{
// Complete
}
CallBackObject.prototype.OnAbort = function()
{
// Abort
}
CallBackObject.prototype.OnError = function(status, statusText)
{
// Error
}
//封装第五步,在回调函数中判断交互是否结束,响应是否正确,并根据需要获取服务器返回的数据,并更新页面
CallBackObject.prototype.ReadyStateChange = function()
{
if( this.XmlHttp.readyState == 1 )
{
this.OnLoading();
}
else if( this.XmlHttp.readyState == 2 )
{
this.OnLoaded();
}
else if( this.XmlHttp.readyState == 3 )
{
this.OnInteractive();
}
else if( this.XmlHttp.readyState == 4 )
{
if( this.XmlHttp.status == 0 )
this.OnAbort();
else if( this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK" )
this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);
else
this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);
}
}