Ajax
使用浏览器内置的一个对象(XmlHttpRequest)向服务器发送请求,服务器返回xml数据或者是文本数据给浏览器,然后在浏览器端,使用这些数据更新部分页面,整个过程,页面无仸何的刷新。
Ajax引擎(即XmlHttpRequest对象),首先为该对象注册一个监听器(该监听器是一个事件处理函数,对状态改变事件(readyStatechange)迚行监听)
Ajax技术特点
1) 页面无刷新
2) 不打断用户的操作,用户的体验好。
3) 按需获取数据,浏览器与服务器之间数据的传输量减少。
4) 是一个标准技术,不需要下载任何的揑件。
5) 可以利用客户端(浏览器)的计算能力。
Ajax代码位置 <script> this is ajax </script>
Ajax编程
step1
获得XmlHttpRequest对象(ie浏览器不支持)
function getXmlHttpRequest(){
var xhr = null;
if((typeof XMLHttpRequest)!='undefined'){
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
return xhr;
}
step2
使用XmlHttpRequest向服务器发送请求
1.发送get请求
var xhr = getXmlHttpRequest();
//get方式,参数添加地址,true表示异步
xhr.open('get','check_ser',true);
//注册监听器,改变产生了readystatechange事件,f1函数处理
xhr.onreadystatechange=f1;
//调用send方法,请求菜真正发送
xhr.send(null);
2.发送post请求
var xhr = getXmlHttpRequest();
xhr.open('post','check_username.do',true);
//必须添加一个消息头content-type
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=f1;
xhr.send('username=zs');
step3
在服务器端,处理请求
step4
在监听器端,处理请求
xhr.onreadystatechange=f1;
function f1(){
//编写相应的处理代码
}
或者
xhr.onreadystatechange=function(){
//编写相应的处理代码
if(xhr.readyState == 4){
//只有readyState等亍4,xhr才完整地接收到了服务器返回的数据。
//获得文本数据
var txt = xhr.responseText;
//获得一个xml dom对象。
var xml = xhr.responseXML;
//dom操作、更新页面
}
};