最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - wait for callback of getJSON finish in jquery - Stack Overflow

programmeradmin2浏览0评论

I has something like this:

<div id="content"></div>

and JS:

function getData(id) {
    $.getJSON('url/to/jsondata',{id: id}, function(data) {
         /** append some data to div#content  **/
         $('#content').data('key', 'value');
     });

then I want to get data of #content in script:

$(document).ready(function() {
    getData(1); // run getData with some id
    console.log($('#content').data('key'));
});

Problem is console.log not run after callback of getJSON finish, so i get a undefined value in log. Which is right way to make it work? Thank!

I has something like this:

<div id="content"></div>

and JS:

function getData(id) {
    $.getJSON('url/to/jsondata',{id: id}, function(data) {
         /** append some data to div#content  **/
         $('#content').data('key', 'value');
     });

then I want to get data of #content in script:

$(document).ready(function() {
    getData(1); // run getData with some id
    console.log($('#content').data('key'));
});

Problem is console.log not run after callback of getJSON finish, so i get a undefined value in log. Which is right way to make it work? Thank!

Share Improve this question asked Aug 20, 2012 at 16:51 Coder53Coder53 231 gold badge1 silver badge3 bronze badges 1
  • @TheZ your ment is an answer - you should put it as one so it can get voted up as an answer. – kinakuta Commented Aug 20, 2012 at 16:53
Add a ment  | 

3 Answers 3

Reset to default 2

Return the deffered object from the ajax function and use the always, done or fail methods on it:

function getData(id) {
    return $.getJSON('url/to/jsondata',{id: id}, function(data) { //return this
         $('#content').data('key', data);
     });
}

$(document).ready(function() {
    getData('content').always(function() { //is returned as deffered object
        console.log($('#content').data('key')); //runs when ajax pleted
    });
});​

You have already defined the callback in your getJSON call. To get the results put your console.log code near in the same function as the /** append some data to div#content **/ ment.

Here's the jQuery documentation for getJSON so you can see which is the correct argument and how you can lay it out: http://api.jquery./jQuery.getJSON/

You should put the log-call in the callback-function like this:

function getData(id) {
    $.getJSON('url/to/jsondata',{id: id}, function(data) {
         /** append some data to div#content  **/
         $('#content').data('key', 'value');

         console.log($('#content').data('key'));
     });
发布评论

评论列表(0)

  1. 暂无评论