1

I am converting dojo to jquery ajax,dojo can get the result but ajax can't here are the codes comparision:

dojo:

var getResourceHandler = dojo.xhrPost( {
  url: feedUrl,
  content: {
      nlsStringKey: key
  },
  sync: true,
  handleAs: "json",
  preventCache: false,
  load: function(data){
      console.debug(data);
      resourceList = data;
  },
  error: function(error){
      console.debug("getNlsStringFromFeed ERROR");
      console.debug(error);
  }

})

and here is the code of jquery ajax

var getResourceHandler = $.ajax({
   method: "POST",
   url: feedUrl,
   data: { nlsStringKey : key },
   dataType:"json",
   cache:true
});

getResourceHandler.done(function(data){
    console.debug(data);
    resourceList = data;
});

getResourceHandler.fail(function(error){
    console.debug("getNlsStringFromFeed ERROR");
    console.debug(error);
});

so ajax didn't get the result, resourceList = null by the end. but dojo got the result, resourceList is not null. couldn't figure out the problem.

Thank you in advance.

ChProgrammer
  • 75
  • 1
  • 7
  • I don't know dojo, but `sync: true` certainly seems to imply that the call is happening synchronously, and so `resourceList` would be set after the cakk was cinokete. As is, in the jQuery version, `resourceList` wouldn't be set until some unspecified time later, when the Ajax call completes. – Paul Roub Jun 12 '17 at 18:02
  • Take a look at [How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re?rq=1), first in the "Related" list on this page. – Paul Roub Jun 12 '17 at 18:02
  • But a much better approach (in terms of responsiveness and user experience) would be to properly handle the asynchronous response. See [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Paul Roub Jun 12 '17 at 18:04
  • Possible duplicate of [How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re) – Paul Roub Jun 12 '17 at 18:05
  • @Paul Roub Thanks a lot, I will try it out! – ChProgrammer Jun 15 '17 at 13:56
  • A very good explanation here: [link] (https://www.aspsnippets.com/Articles/jQuery-AJAX-Async-False-Synchronous-call-and-Async-True-Asynchronous-call-difference.aspx) – ChProgrammer Jun 15 '17 at 14:06

0 Answers0