jQuery ajax request proxy
How I can do the following operation with jQuery:
- Some library send ajax request via $.ajax
- I need to catch all these requests, a开发者_JS百科nd in some cases abort them, and instead pass off another data.
I found, that in jQuery 1.5
there were introduced new methods, such as ajaxPrefilter
and ajaxTransport
. I also tried ajaxSetup
with beforeSend
,
but I can't achieve 2 points of these working...
Don't use this unless until you are damn sure about what you are doing
I am not sure about the ajax intercepter libraries. But i can tell you the nasty hack
Take copy of your original jquery ajax instance
var oldAjaxInstance; //some global variable oldAjaxInstance = $.ajax; //in document load
And assign your intercepert method to the $.ajax pointer
$.ajax = myAjaxwrapper;
myAjaxwrapper looks womething like this
function myAjaxwrapper(a) {
//your logic to change the request data's
if (you are ok to allow the ajax call) {
//re Assgin the actual instance of jquery ajax
$.ajax =oldAjaxInstance;
//and call the method
$.ajax(a);
}
//Otherwise it wont be called
}
And onsucess of your ajax call reassign your ajax wrapper to jquery ajax
oldAjaxInstance = $.ajax; $.ajax = myAjaxwrapper;
Strange, but it works only in couple with two methods :)
function enableFakeAjax(isEnable, fakeData) {
isFakeAjax = isEnable;
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (isFakeAjax) {
jqXHR.abort();
originalOptions.success(fakeData);
}
});
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
if (isFakeAjax) {
jqXHR.abort();
}
}
});
}
enableFakeAjax(true, jsonData);
isFakeAjax = false;
OK, this issue was fixed in jQuery 1.5.1.
精彩评论