Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
.
dataTypes
An optional string containing one or more space-separated dataTypes
handler
A handler to set default values for future Ajax requests.
A typical prefilter registration using $.ajaxPrefilter()
looks like this:
1
2
3
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
where:
options
are the request optionsoriginalOptions
are the options as provided to the $.ajax()
method, unmodified and, thus, without defaults from ajaxSettings
jqXHR
is the jqXHR object of the requestPrefilters are a perfect fit when custom options need to be handled. Given the following code, for example, a call to $.ajax()
would automatically abort a request to the same URL if the custom abortOnRetry
option is set to true
:
1
2
3
4
5
6
7
8
9
10
var currentRequests = {};
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
if ( options.abortOnRetry ) {
if ( currentRequests[ options.url ] ) {
currentRequests[ options.url ].abort();
currentRequests[ options.url ] = jqXHR;
Prefilters can also be used to modify existing options. For example, the following proxies cross-domain requests through https://mydomain.net/proxy/:
1
2
3
4
5
6
$.ajaxPrefilter(function( options ) {
if ( options.crossDomain ) {
options.url = "https://mydomain.net/proxy/" + encodeURIComponent( options.url );
options.crossDomain = false;
If the optional dataTypes
argument is supplied, the prefilter will be only be applied to requests with the indicated dataTypes. For example, the following only applies the given prefilter to JSON and script requests:
1
2
3
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
The $.ajaxPrefilter()
method can also redirect a request to another dataType by returning that dataType. For example, the following sets a request as "script" if the URL has some specific properties defined in a custom isActuallyScript()
function:
1
2
3
4
5
$.ajaxPrefilter(function( options ) {
if ( isActuallyScript( options.url ) ) {
This would ensure not only that the request is considered "script" but also that all the prefilters specifically attached to the script dataType would be applied to it.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3