Reputation: 3407
Can you please explain to me the simplest way on how the AJAX prefiltering in jQuery works? Sorry I'm a newbie in using AJAX.
Is it for customizing requests in the server? Thanks.
I'm referring to this site but still can't get it.
Upvotes: 2
Views: 9485
Reputation: 8761
$.ajaxPrefilter
is used to alter the ajax requests before they are initiated. These are used as per the application requirements.
Like,
attaching a user session id in every request as a header to authenticate an user.
$.ajaxPrefilter(function (params, originalOptions, jqXHR)
{
jqXHR.setRequestHeader("APP-SECURE-TOKEN","abc1234dfg5678");
}
It attaches a header to all requests, to validate the user. If no token is present, the request can be aborted and redirected to the login page.
adding a version namespace before every requests.
$.ajaxPrefilter(function (params, originalOptions, jqXHR)
{
params.url = "/v1/"+params.url;
}
It makes easy to upgrade the namespaces in later versions where we don't need to search and modify at every place where an ajax request is made.
cancel requests requesting the same resource.
var requests = {};
$.ajaxPrefilter(function (params, originalOptions, jqXHR)
{
if(requests[params.url])
{
requests[params.url].abort();
}
requests[params.url] = jqXHR;
}
If a file is being download, it can be aborted and downloaded fro start. Else, alert can be thrown that the file is being download.
Block crossDomain requests.
$.ajaxPrefilter(function (params, originalOptions, jqXHR)
{
if(params.crossDomain)
{
jqXHR.abort();
}
}
Upvotes: 0
Reputation: 6025
Have a read of the documentation at http://api.jquery.com/jquery.ajaxprefilter/ this function is basically used to alter the data that is sent through to your server before it is sent.
An example I have used specifically is
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
options.data = $.param($.extend(originalOptions.data||{}, {
timeStamp: new Date().getTime()
}));
});
Which takes the original data that was to be sent through an adds another parameter with a timestamp. This was useful to get around iOS's problem with caching post requests without having to add a timestamp to each individual request.
Upvotes: 2