$ .when (). done () doesn't work as expected

I need to load html to a page via jquery ajax. Then, after the html is loaded, I want to parse it for specific data that will be in the loaded html and use it to generate map markers. So I need the load method to execute synchronously so that the html is definitely loaded before my setMarkers () method tries to parse it.

$.when($("#orders").load("datadisp.aspx")).done(function () {
    setMarkers();
});

      

I thought the current setup I have should do just that, but I can tell from the debugger that setMarkers () is still called before the download is complete because when I set a breakpoint on setMarkers () and check the html after from the way it hit that breakpoint, I can see that the expected html has not been loaded yet. Can anyone show me the correct way to solve this problem? Thank.

+3


source to share


3 answers


The problem is it load()

doesn't return a promise that can be used with $.when

. If you want to execute some code after completion load()

, put it in a callback handler:



$("#orders").load("datadisp.aspx", function() {
    setMarkers();
});

      

+6


source


I think you are using jQuery.when () incorrectly because this method is part of Deferred , which implements the Promise interface , and the jqXHR returned by jQuery.ajax () implements the Promise interface , giving them all the properties, methods, and behavior of the Promise (see . "Deferred Object" for more information)

The best approach might be as follows:

$.when(
  $.ajax({
    type: "GET",
    url: "datadisp.aspx"
    //dataType: "html"
  })
).then(
  function done(data) {
    console.info("done!");
    console.log(data);
    setMarkers();
  },
  function fail(jqXHR, textStatus) {
    console.log(jqXHR);
  }
);

      



You can just use jQuery.ajax () and transport / process jqXHR : fooobar.com/questions/2240413 / ...

Or you can use a Deferred object with jQuery.when () to handle the Promise interface : fooobar.com/questions/2240414 / ...

0


source


If you want to load a WebForm or Html page, use the load and pass function in your load handler and make the rest stuff.

$("#orders").load("datadisp.aspx", setMarkers);

/*Handler function*/
function setMarkers(data)
{
/*Code*/
}

      

0


source







All Articles