jeudi 6 février 2020

How to call callback from ajax from inside the factory function

Operations is a factory method that has a bunch of utility functions like Get, Post etc. I would like to capture the response of Ajax call in the callback function and that callback function in outside the factory method as given in the code below.

var Operations = function() {
    get: function(url, scallback) {
      var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
      xhr.open('GET', url );
      xhr.onreadystatechange = function( ) {
        if (xhr.readyState > 3 && xhr.status == 200) {
          scallback(xhr.responseText);
        } else if (xhr.status == 400) {
          alert("App encountered an error. Please refresh the page and try again!")
        }
      };

      return xhr;
    },
}

** Usage **

var ops = new Operations();
ops.post('https://reqres.in/api/user/2', function(response) {
  //Here I want to capture the ajax response
   console.log(123);
});




Aucun commentaire:

Enregistrer un commentaire