ajaxPrefilter and ajaxTransport processing simulating image in JQuery
- 2020-06-15 07:48:05
- OfStack
//////////////////////////////////////////////////////////////////
// options Is the option of the request //
// originalOptions Value as provided to Ajax Method unmodified option, therefore, no ajaxSettings The default value in Settings //
// jqXHR Is the request jqXHR object //
//////////////////////////////////////////////////////////////////
$.ajaxPrefilter("image", function(options, originalOptions, jqXHR) {
// Convert types by preprocessor
if (options.test) {
options.type = 'GET'
}
// Increase the prefix
options.url = "http://img.mukewang.com/" + options.url
});
///////////////////////
// Request distributor 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(){
// perform 1 An asynchronous HTTP ( Ajax ).
var ajax = $.ajax({
test : true, // test
url : '547d5a45000156f406000338-590-330.jpg',
dataType : 'image',
type : 'POST',
data: {
foo: ["bar1", "bar2"]
},
// This object is used for Settings Ajax The context of the associated callback function
context: document.body,
// A callback function used to modify a request before it is sent jqXHR
beforeSend: function(xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
show(' Local events beforeSend')
},
// The callback function completes the request ( request success and error All subsequent calls )
complete: function() {
show(' Local events complete')
},
error: function() {
show(' Local events error This function is called when the request fails ')
},
success: function() {
show(' Local events success')
}
})
ajax.done(function() {
show('done')
}).fail(function() {
show('fail')
}).always(function() {
show('always')
})