我们知道 Ajax 的底层实现其实是很简单的(抛开IE不说),标准的 w3c 直接提供了 XMLHttpRequest 方法。我们主要站在设计的角度来理解,如何设计出低耦合高内聚的代码 jQuery 对 Ajax 的处理主要体现在对浏览器兼容,数据的处理过滤以及各种事件的封装上,主要有以下几部分扩展:
提供快捷接口 提供底层接口 提供数据序列化 提供全局 Ajax 事件处理
分析下面一个demo
给 document 绑定 ajaxStart、ajaxComplete 回调事件,trigger 绑定一个点击事件。通过 click 触发事件发送一个 ajax 请求,并且通过 complete、done、ajaxStart、ajaxComplete 返回状态回调。
$(document).ajaxStart(function() { console.log(arguments) }).ajaxComplete(function() { $(".log").text("Triggered ajaxComplete handler."); }); $(".trigger").click(function() { //发送ajax请求 $.ajax({ url: "php.html", context: document.body, complete: function() { console.log(this) } }).done(function() { console.log(this) }); });
这里实现比较特别的地方,针对 ajax 提供 3 种回调方式:
换句话说,针对ajax的请求,每一步的状态、成功、失败或者进行中,我们有 3 种方式可以监听,但是每一种还是有各自的区别:
那么我们思考下为什么要设计这么多接口?这么多功能怎么融合在一起的?
<!doctype html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <script src="http://code.jquery.com/jquery-latest.js"></script> <title>ajax</title> <style type="text/css"> div{ width: 150px; height: 50px; border: 5px solid #ccc; } </style> </head> <body> <div id="aaron1" style="background:yellow;border:20px solid #ccc;">点击触发Ajax成功请求</div> <div id="aaron2" style="background:red;border:20px solid #ccc;">点击触发Ajax失败请求</div> </br> 回调触发的循序 <ul></ul> <script type="text/javascript"> var $ul = $('ul') function show(data){ $ul.append('<li>'+ data +'</li>'); } //全局事件触发 $(document).ajaxSend(function() { show('全局事件ajaxSend ') }).ajaxSuccess(function() { show("全局事件ajaxSuccess"); }).ajaxError(function() { show("全局事件ajaxError"); }).ajaxComplete(function() { show('全局事件ajaxComplete') }) function ajax(url) { //执行一个异步的HTTP(Ajax)的请求。 var ajax = $.ajax({ url: url, dataType: 'script', //这个对象用于设置Ajax相关回调函数的上下文 context: document.body, //请求发送前的回调函数,用来修改请求发送前jqXHR beforeSend: function(xhr) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); show('局部事件beforeSend') }, //请求完成后回调函数 (请求success 和 error之后均调用) complete: function() { show('局部事件complete') }, error: function() { show('局部事件error请求失败时调用此函数') }, success: function() { show('局部事件success') } }) ajax.done(function() { show('done') }).fail(function() { show('fail') }).always(function() { show('always') }) } $("#aaron1").click(function() { $ul.empty(); ajax("http://code.jquery.com/jquery-latest.js") }); $("#aaron2").click(function() { $ul.empty(); ajax("#") }); </script> </body> </html>