Ajax的基本概念和核心技术:Ajax技术的核心就是XMLHttpRequest对象。这个对象充当着浏览器当中的脚本与服务器之间的中间人的角色。以往的请求都由浏览器发出,而JavaScript可以通过这个对象自己发送请求,同时也自己处理响应。
Ajax技术的基本应用:
首先,我们需要创建一个XMLHttpRequest,不同的浏览器有不同的创建方式,所以为了兼容各种版本的浏览器,创建XMLHttpRequest对象的代码总结如下:
function getHTTPObject(){
if(typeof XMLHttpRequest == 'undefined')
XMLHttpRequest=function(){
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
return false;
}
return new XMLHttpRequest();
}
这样,在你的脚本中要使用XMLHttpRequest时,可以直接将这个新对象赋值给一个变量:var requesr = getHTTPObject();
然后我们便可以使用XMLHttpRequest对象来发送请求或者来处理响应了。
相关代码如下:
function getNewContent(){
// 把在函数中创建的xmlhttprequest对象赋值给变量
var request=getHTTPObject();
if(request){
// 利用对象中的open方法来指定服务器上要打开的文件,这个方法中的第三个参数用来确定请求是否以异步方式发送和处理
request.open("GET",'example.txt', true);
// 给这个对象添加事件处理函数:他会在服务器给xmlhttprequest发送相应的时候被触发执行,在这个处理函数中,可以根据服务器的具体响应做相应的处理。
request.onreadystatechange=function(){
// 当xmlhttprequest对象的属性readystate的值为数字4时,就可以访问服务器发送回来的数据了
if(request.readyState==4){
// 在文档中添加一个p元素节点
var para=document.createElement('p');
// 使用xmlhttprequest对象的responetext属性来访问服务器发送回来的文本数据:把文本节点赋值给变量txt。
var txt=document.createTextNode(request.responseText);
// 把文本节点txt插入到段落节点中。
para.appendChild(txt);
// 把段落节点插入到id为new的元素节点中。
document.getElementById('new').appendChild(para);
}
};
// 在指定了请求的目标,也明确了如何处理相应之后,就可以使用send方法来发送请求了。
request.send(null);
}
// 当浏览器不支持xmlhttprequest对象时,做出如下的用户提示。
else
alert("sorry your browser doesn't support XMLHttpRequest");
}
注意!:使用xmlhttprequest对象发送的请求只能访问与其所在的HTML文件处于同一个域中的数据,在这个实例中我在HTML文件所在的文件夹中创建了一个example.txt文件来使用。
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
<script type="text/javascript">
window.οnlοad=function(){
function getHTTPObject(){
if(typeof XMLHttpRequest == 'undefined')
XMLHttpRequest=function(){
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e){}
return false;
}
return new XMLHttpRequest();
}
function getNewContent(){
var request=getHTTPObject();
if(request){
request.open("GET",'example.txt', true);
request.onreadystatechange=function(){
if(request.readyState==4){
var para=document.createElement('p');
var txt=document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById('new').appendChild(para);
}
};
request.send(null);
}
else{
alert("sorry, your browser doesn't support XMLHttpRequest");
}
}
getNewContent();
};
</script>
</head>
<body>
<div id="new"></div>
</body>
</html>
一切准备完毕之后,example.txt文件中的文本内容就会出现在id为new的第v元素中,如图所示: