开发者

How to wait for ajax to get data, using JSON, before continuing execution?

I'm creating a program that gets data from a server using AJAX/JSON and then used that data to draw onto a canvas (html5). I have a function that when called, does some initialization and then calls this function:

function getClimateData(climateElement) {
    $.ajax(
    {
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "/Climate/yearInformation" + climateElement,
        data: "{}",
        dataType: "json",
        success: function (data) {
            weatherData = data;
        },
        error: function (xhr, err) {
            // Note: just for debugging purposes!
            alert("readyState: " + xhr.readyState +
                    "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    }
    )
};

The problem is that before all the data has arrived, the calling function continues and draws some stuff on my canvas, bas开发者_JAVA技巧ed on the data (which isn't there). This only happens sometimes.

How can I make sure the data has arrived before execution continues ?


Do the work…

    success: function (data) {
        weatherData = data;
        // <------------------ HERE! 
    },

… and not in the calling function.

That is the point of having a callback function.


Move the code that draws based on the data to a separate function call in the success function - or just put the code directly in the success function.

...
success: function (data) { 
  // use data to do your drawing
},
...


It is theoretically possible to put the request into synchronous mode using async: false but it's usually a bad idea.

The best way to deal with this is to change your script's structure so everything dependent on the request happens in the success callback (or gets called from there).


You should put the drawing function in your success callback. This way, the drawing functionality is only triggered when the data arrives.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜