AsGoodAsItGets
AsGoodAsItGets

Reputation: 3181

Is there any way to manipulate the existing preFilters in jQuery?

The jQuery.ajaxPrefilter() functions allows to add preFilters to the built-in ones, but there doesn't seem to be a way to get access to the internal jQuery preFilters. In jQuery 1.11.1 I see there is a private preFilters object declared in line 8568, but I don't see a method to return or manipulate this.

I've added my preFilter already, but some of the existing preFilters (namely for dataType = 'script') are messing with it. Plus, I want to be able to dynamically add/remove/re-arrange preFilters at runtime.

This is a codepen illustrating the idea: http://codepen.io/anon/pen/Yqzwqp

When you check the checkbox, all GET calls are automatically converted to POST. When you uncheck it, they go back to normal. The only shorthand method that doesn't respect that is $.getScript().

Any ideas?

Upvotes: 1

Views: 584

Answers (1)

guest271314
guest271314

Reputation: 1

You can use beforeSend option of $.ajaxSetup() .abort(), .ajaxError() to handle errors

$.ajaxSetup({    
  beforeSend: function(jqxhr, settings) {
    if (settings.type === "GET" && settings.dataType === "script") {
      // abort `$.getScript()`
      jqxhr.abort();
      // convert `type` to `POST`
      settings.type = "POST";
      // convert `dataType` to expected response from `POST`
      settings.dataType = "json";
      settings.cache = false;
      // remove query string from , replace `url`
      settings.url = "script2.js"; /* settings.url.replace(/\?.*$/, ""); */
      console.log("beforeSend", settings);
      // use updated `settings` object
      $.ajax(settings)
    }
  },
  complete: function(data, textStatus, jqxhr) {
    console.log("complete", data)
  }
});

$(document).ajaxError(function(event, jqxhr, settings, errorThrown) {
  // handle aborted `$.getScript()` requests
  console.log("err", event, jqxhr, settings, errorThrown)
});
// `request` should be converted into `$.ajax({type:"POST"})`
var request = $.getScript("script1.js");

plnkr http://plnkr.co/edit/Q9PmTVnO4LoWvvjmIBLs?p=preview

Upvotes: 1

Related Questions