|
//////////////////////////////////////////////////////////////////
// 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) ? "success" : "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')
})
|