javascript 在 jquery 中等待 getJSON 的回调完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12041769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:08:39  来源:igfitidea点击:

wait for callback of getJSON finish in jquery

javascriptjquerycallbackgetjson

提问by Coder53

I has something like this:

我有这样的事情:

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

and JS:

和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:

然后我想在脚本中获取#content 的数据:

$(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!

问题是在 getJSON 完成回调后没有运行 console.log,所以我在日志中得到一个未定义的值。哪个是使它工作的正确方法?感谢!

采纳答案by adeneo

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

从 ajax 函数返回延迟对象并在其上使用 always、done 或 fail 方法:

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 completed
    });
});?

回答by TheZ

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

您已经在调用中定义了回调getJSON。要获得结果,请将您的 console.log 代码放在与/** append some data to div#content **/注释相同的函数中。

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.com/jQuery.getJSON/

这是 getJSON 的 jQuery 文档,因此您可以查看哪个是正确的参数以及如何布局:http: //api.jquery.com/jQuery.getJSON/

回答by Mario Sannum

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'));
     });