ajax详细解读

来源:互联网 发布:知乎 西安文都考研 编辑:程序博客网 时间:2024/06/04 18:34

1 什么是ajax?

ajax,全称为:asynchronous javascript and xml(异步的javascript和xml),是一种用来改善用户体验的技术,其本质是利用浏览器内置的一种特殊对象(XMLHttpRequest)异步(既发送请求时,浏览器不会销毁当前页面,用户可以继续在当前页面做其他操作)的向服务器发送请求,并且利用服务器返回的数据(不再是一个完整的页面,只是部分数据,一般使用文本或者xml返回),来部分更新当前页面。使用ajax技术后,页面无刷新,并且不打断用户的操作。

2 传统的web应用

这里写图片描述

3 使用ajax后的web应用

引用块内容

4 ajax的编程步骤

step1:获取ajax对象

由于各版本浏览器的兼容性问题,所以获取ajax对象需要区分IE浏览器和非IE浏览器    var xhr = null;    if(window.XMLHttpRequest){        xhr  = new XMLHttpRequest();//非IE    }else {        xhr  = new ActiveXObject('Microsoft.XMLHttp');//IE    }

step2:发送请求

    xhr.open('请求方式','请求地址','异步还是同步');    请求方式:get/post    请求地址:如果是get请求,请求参数需要添加到请求地址的后面    异步还是同步:true表示异步请求,false表示同步请求(ajax发出请求时,浏览器会锁定当前页面,直到ajax请求处理完毕)。    例子:xhr.open('get','send.do?username=tom',true);

step3:编写服务器代码

 服务器一般不需要返回完整的代码,只需要返回部分数据,比如一个简单的字符串、xml、json等。

step4:编写监听器

xhr.onreadystatechange=function (){    if(xhr.readyState == 4){        //获得服务器返回的数据        var txt = xhr.responseText;        //dom操作    }};xhr.send(null);

5 ajax的get方式和post方式

get方式:

window.onload = function(){    var xhr = null;    if(window.XMLHttpRequest){        xhr  = new XMLHttpRequest();//非IE    }else {        xhr  = new ActiveXObject('Microsoft.XMLHttp');//IE    }    xhr.open('get','send.do?username=tom',true);    xhr.onreadystatechange=function (){    if(xhr.readyState == 4){        //获得服务器返回的数据        var txt = xhr.responseText;        //dom操作    }    };    xhr.send(null);}

post方式:
因为按照http协议的要求,如果发送的post请求,请求数据包里面,应该有一个消息头 content-type。但是,ajax对象默认没有,所以,需要调用setRequestHeader方法。

window.onload = function(){    var xhr = null;    if(window.XMLHttpRequest){        xhr  = new XMLHttpRequest();//非IE    }else {        xhr  = new ActiveXObject('Microsoft.XMLHttp');//IE    }    xhr.open('get','send.do',true);    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');    xhr.onreadystatechange=function (){    if(xhr.readyState == 4){        //获得服务器返回的数据        var txt = xhr.responseText;        //dom操作    }    };    xhr.send('username=' + $F('username'));}

6 发送get请求的编码问题

ie浏览器内置的ajax对象,对中文参数使用gbk编码,而其它浏览器(firefox,chrome)使用utf8编码。服务器端默认使用iso-8859-1去解码。

解决方案:
step1,让服务器对get请求中的参数使用指定的编码
格式进行解码。
比如,对于tomcat,可以修改 conf/server.xml
URIEncoding=”utf-8”
step2,对请求地址,使用encodeURI函数进行统一的
编码(utf-8) (encodeURI(请求地址))

7 发送post请求的编码问题

所有浏览器内置的ajax对象都会使用utf-8进行编码。

解决方案:
request.setCharacterEncoding(“utf-8”);

8 jquery对ajax的支持

$.ajax({    type: "POST",    url: 'send.do',    dataType: "json",//json字符串    success: function(data) {//返回的数据    }});
0 0