JQuery ajax proxy

How can I do the following operation with jQuery:

  • Some library sends ajax request through $ .ajax
  • I need to catch all these requests, and in some cases interrupt them, and instead data.

I found that jQuery 1.5new methods were introduced in, such as ajaxPrefilterand ajaxTransport. I also tried ajaxSetupwith beforeSend, but I can not reach 2 points of these workers ...

+3
source share
3 answers

OK, this problem has been fixed in jQuery 1.5.1.

0
source

Do not use this until you are sure what you are doing.

I am not sure about the ajax gateway libraries. But I can tell you a nasty hack.

  • Make a copy of the original jquery ajax instance

          var oldAjaxInstance; //some global variable
          oldAjaxInstance = $.ajax;  //in document load
    
  • intercepert $.ajax

          $.ajax = myAjaxwrapper;
    

myAjaxwrapper

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
}
  • ajax ajax jquery ajax

               oldAjaxInstance = $.ajax;  
               $.ajax = myAjaxwrapper;
    
0

, :)

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;
0

Source: https://habr.com/ru/post/1789717/


All Articles