简体   繁体   中英

Javascript callback function inside ajax

how would i do this?

function DoStuffAndCallBack(callback){
      $.get( "ajax/test.html", function( data ) {
      callback();

    });
}

DoStuffAndCallBack(DoneFunction);

function DoneFunction(){
  console.log('done stuff');
}

I am getting 'callback' as undefined.Is there a way to do this, i know there are promises and what not but how can i do this in this instance.

It looks like the "callback" is loosing its context inside your inner function ie inside the ajax call.

Try this -

function DoStuffAndCallBack(callback){
    this.callback = callback;
    var self = this;
    $.get( "ajax/test.html", function( data ) {
      self.callback();
    });
}

DoStuffAndCallBack(DoneFunction);

function DoneFunction(){
  console.log('done stuff');
}

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