JQuery中模拟image的ajaxPrefilter与ajaxTransport处理
JQuery中模拟image的ajaxPrefilter与ajaxTransport处理
发布时间:2016-12-30 来源:查字典编辑
摘要:////////////////////////////////////////////////////////////////////op...

////////////////////////////////////////////////////////////////// // options 是请求的选项 // // originalOptions 值作为提供给Ajax方法未经修改的选项,因此,没有ajaxSettings设置中的默认值 // // jqXHR 是请求的jqXHR对象 // ////////////////////////////////////////////////////////////////// $.ajaxPrefilter("image", function(options, originalOptions, jqXHR) { //通过预处理器转化类型 if (options.test) { options.type = 'GET' } //增加前缀 options.url = "http://img.mukewang.com/" + options.url }); /////////////////////// // 请求分发器 transports // /////////////////////// $.ajaxTransport("image", function(s) { if (s.type === "GET" && s.async) { var image; return { send: function(_, callback) { image = new Image(); function done(status) { if (image) { var statusText = (status == 200) "error", tmp = image; image = image.onreadystatechange = image.onerror = image.onload = null; callback(status, statusText, { image: tmp }); } } image.onreadystatechange = image.onload = function() { done(200); }; image.onerror = function() { done(404); }; show(s.url) image.src = s.url; }, abort: function() { if (image) { image = image.onreadystatechange = image.onerror = image.onload = null; } } }; } }); $("#test").click(function(){ //执行一个异步的HTTP(Ajax)的请求。 var ajax = $.ajax({ test : true, //测试 url : '547d5a45000156f406000338-590-330.jpg', dataType : 'image', type : 'POST', data: { foo: ["bar1", "bar2"] }, //这个对象用于设置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') })

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类