关于ajax的一些总结

来源:互联网 发布:识别图片真假软件 编辑:程序博客网 时间:2024/05/17 00:14

Ajax

定义

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。AJAX 是在不重新加载整个页面的情况下, 与服务器交换数据并更新部分网页的技术 .

XMLHttpRequest 对象

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

新的浏览器都是使用XMLHttpRequest对象:

new XMLHttpRequest().var xmlhttp;if (window.XMLHttpRequest){    // code for IE7+, Firefox, Chrome, Opera, Safari    xmlhttp=new XMLHttpRequest();}else{    // code for IE6, IE5    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

为了应对所有浏览器 , 写法如下 :

var xmlhttp;if (window.XMLHttpRequest){    // code for IE7+, Firefox, Chrome, Opera, Safari    xmlhttp=new XMLHttpRequest();  }else{    // code for IE6, IE5    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }

如何向服务器发送请求 , 我们使用XMLHttpRequest的open()和send()方法 :

xmlhttp.open(METHOD,URL,ASYNC);xmlhttp.send();
方法 描述 open(method,url,async) 规定请求的类型、URL 以及是否异步处理请求 method:请求的类型;GET 或 POST url:文件在服务器上的位置 async:true(异步)或 false(同步) send(string) 将请求发送到服务器, string 仅适用于 post 请求

Async = true(异步请求)当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数

xmlhttp.onreadystatechange=function()  {  if (xmlhttp.readyState==4 && xmlhttp.status==200)    {    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }  }xmlhttp.open("GET","test1.txt",true);xmlhttp.send();

Async = false(同步请求) 不推荐使用 async=false,但是对于一些小型的请求,也是可以的。
请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。

xmlhttp.open("GET","test1.txt",false);xmlhttp.send();document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Jquery.ajax

基本形式

$.ajax({    type:"POST",//默认GET    url:URL,//发送请求的地址    dataType : "json",//如果不指定,jquery会根据http包的MIME信息智能判断    cache : true,//默认缓存为true    async : false,//默认是否异步为true    success : function(data,textStatus) {        //do something when the Ajax request succeed    },    error:function(XMLHttpRequest, textStatus, errorThrown){        //do something when the Ajax request failed    },    beforeSend:function(XMLHttpRequest){        //do something before send    },    complete:function(XMLHttpRequest,textStatus){        //do something whether the Ajax request failed or not    },    dataFilter:function(data,dataType){        //filter the data before the success function execute    }    });

上面的 Jquery.ajax也可以简写成Jquery.get或是Jquery.post , 就是相当于直接指定了type .

ajax请求遇到session过期的处理

普通非ajax请求在遇到session过期时 , 可以用:

response.sendRedirect("/login.html")

, 或是用

request.getRequestDispatcher("/login.html").forward(request, response);

两者区别是 ,前者在返回给浏览器,浏览器重新发送一个新的request请求给服务器,request变了;后者是在服务器内部实现请求转发,是同一个request,浏览器发过去一个请求,中间被服务器转发过一次,地址栏显示的地址还是之前那个地址,但是返回的页面已经不是之前请求的页面了.

对于ajax请求,在遇到session过期的情况下,上述两个方法都是不可取的, 因为ajax请求的response信息是返回给回调函数的,所以只能根据回调函数的返回信息,来确定是否过期并且在回调函数里发送请求; 这里因为一个项目会有很多ajax请求,我们不可能在每个ajax请求都写一个这样的判断, 这里给出一个办法, 就是重写jquery的ajax方法, 这样所有的ajax请求在遇到session失效时, 由重写的ajax方法统一来判断,具体代码如下:

前台Jquery ajax重写代码参考:

(function($){    //备份jquery的ajax方法    var _ajax=$.ajax;    //重写jquery的ajax方法    $.ajax=function(opt){        //备份opt中error和success方法        var fn = {            error:function(XMLHttpRequest, textStatus, errorThrown){},            success:function(data, textStatus){}        }        if(opt.error){            fn.error=opt.error;        }        if(opt.success){            fn.success=opt.success;        }        //扩展增强处理        var _opt = $.extend(opt,{            error:function(XMLHttpRequest, textStatus, errorThrown){                //错误方法增强处理                fn.error(XMLHttpRequest, textStatus, errorThrown);            },            success:function(data, textStatus){                //成功回调方法增强处理                var status = XMLHttpRequest.status;                if(status=='状态码'){                    var url =   XMLHttpRequest.getResponseHeader("Location");                    alert("用户已经过期或者已经在其他地方登陆");                    window.location.href = url;                    return;                }                fn.success(data, textStatus);            }        });        _ajax(_opt);    };})(jQuery);

后台JAVA代码参考:

//如果是ajax请求响应头会有,x-requested-with;  if (request.getHeader("x-requested-with") != null   && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){      response.setStatus("状态码");//指定一个状态码 作为重写过后的ajax方法的判断依据    response.setHeader("Location",request.getContextPath()+"/login.html");     return false;} 
0 0
原创粉丝点击