$ .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.
source to share
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 / ...
source to share