简体   繁体   中英

return AJAX inside AJAX call

I want to return the second ajaxcall as result of the ajax function, can anyone help me.

private ajax(url: string, method:string, data:any = null) {
    var _this = this;
    return this.csrfWithoutDone().done(function (res) {
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': res
        }
      });
      return $.ajax({
        url: _this.baseUrl + url,
        type: method,
        data: data,
      });
    });
  }

the csrfWithoutDone function:

return $.ajax({
      url: _this.baseUrl + '/api/csrf',
      type: 'GET'
    });

BTW: this is writen in typescript but if you replace private with function and remove the : (type) it works in js too.

What you should do is CHAIN the calls.

The .done() function is asynchronous. Therefore it will execute whatever you pass it as an argument when the response is back. That function's returned value goes nowhere.

What you should do instead is: foo.then(function() { /*step 1 /}).then(function({ / step 2 */ })

I would suggest reading a little bit about asynchrounousity in Javascript.

This is the way you would do it with promises, I have never worked with jQuery so the syntax might differ.

edit: I would add that there is no way to return the response value in your initial function. the best you can do is return the jqXHR object, And then call the "then()" or "done()" from the caller.

You should return a Promised object in your ajax function, to be able to find out if your request is done or not. Since you are using jQuery, you can use Deferred Objects :

function ajax(url, method, data) {
    var _this = this;

    // Create a deferred object
    var dfd = $.Deferred();

    this.csrfWithoutDone().done(function (res) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': res
            }
        });

        $.ajax({
            url: _this.baseUrl + url,
            type: method,
            data: data,
        }).done(function (response) {
            // your inner ajax has been done
            // tell your promised object and pass the response to it
            dfd.resolve(response);
        });
    });

    // return promised
    return dfd.promise();
}

// call your ajax function, it is a promised object
var ajaxRequest = ajax();

// so you can wait for the response
ajaxRequest.done(function (response) {
    // your ajax has been done and you have the response
    console.log(response);
});

I've implemented a simple code to find out how Promised object works:

 function ajax() { var dfd = $.Deferred(); setTimeout(function () { dfd.resolve('Hello World'); }, 1000); return dfd.promise(); } var testResult = ajax(); testResult.done(function (response) { alert(response); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can use native Promise Object as well, and maybe you need polyfill, to support all browsers, see Can I Use .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM