利用 jQuery 低階擴展點 $.ajaxPrefilter(預處理選項)與 $.ajaxTransport(自訂傳輸機制),可透明地將 dataType: "image" 的 AJAX 請求轉為 Image 物件載入,繞過同源策略限制,實現跨域圖片獲取與統一錯誤處理。
// 1. 預處理器:統一轉為 GET、加上圖片伺服器前綴
$.ajaxPrefilter("image", function(options, originalOptions, jqXHR) {
if (options.test) { options.type = 'GET'; }
options.url = "https://img.mukewang.com/" + options.url;
});
// 2. 傳輸器:僅處理 GET 且非同步請求
$.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";
var 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); };
image.src = s.url;
},
abort: function() {
if (image) {
image = image.onreadystatechange = image.onerror = image.onload = null;
}
}
};
}
});
// 3. 使用範例
$("#test").click(function() {
$.ajax({
test: true,
url: '547d5a45000156f406000338-590-330.jpg',
dataType: 'image',
type: 'POST', // 會被 prefilter 轉為 GET
data: { foo: ["bar1", "bar2"] },
context: document.body,
beforeSend: function(xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
},
complete: function() { console.log('complete'); },
success: function(img) { console.log('success', img); },
error: function() { console.log('error'); }
}).done(function() { console.log('done'); })
.fail(function() { console.log('fail'); })
.always(function() { console.log('always'); });
});
dataType: "image" 請求,強制轉為 GET 並重寫 URL,移除請求主體(圖片載入不支援 POST body)send/abort 介面,內部建立 new Image(),綁定 onload/onerror/onreadystatechange,載入完成後透過 callback(status, statusText, {image}) 將 HTMLImageElement 傳回成功回調abort 與 done 中均釋放事件參考與物件,防止洩漏此模式展示了 jQuery AJAX 架構的極高擴充性,同理可擴展支援 Script、JSONP 等自訂傳輸類型。