为什么在控制台中看不到此JSON? [英] Why can't I see this JSON in the console?

查看:280
本文介绍了为什么在控制台中看不到此JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下jQuery,为什么不能在$.getJSON()函数之外使用json var?如果我将console.log()放在$ .getJSON回调函数中,它可以工作,但为什么不在外面?

With the following jQuery, why can't I use the json var outside of the $.getJSON() function? If i put the console.log() inside the $.getJSON callback function it works, but why not outside?

function getMyJson() {
    var json;
    $.getJSON('/cdnBuffet.json', function (data) {
        json = data;
    });

    console.log(json);  // nothing is shown in console here. Why?
}

推荐答案

JavaScript通常用作带有回调的异步函数-试图将其强制为同步函数通常是一个初学者的错误,人们稍后会后悔.

JavaScript generally works as async functions with callbacks -- trying to force this into sync functions is generally a beginners mistake which people regret later.

您的ajax调用通常就是这样的异步调用,而您指定的function是当ajax调用完成时执行的回调.

Your ajax call is typically such a async call, and the function you specify is the call back which is executed when the ajax call completes.

在您的代码中,console.log在ajax调用完成之前执行.

In your code, the console.log executes before the ajax call completes.

只需将console.log移动到回调内部,如下所示:

Just move the console.log inside the callback like this:

function getMyJson() {
    var json;
    $.getJSON('/cdnBuffet.json', function (data) {
        json = data;
        console.log(json);  // will now show the data...
    });
}

如果您实际上需要将其返回给调用函数getMyJson,则只需扩展getMyJson的编程范例即可使其具有回调,例如:

If you actually need to return it to the calling function getMyJson, just extend the programming paradigm for getMyJson to have a callback as well, like:

function getMyJson(myCallback) {
    var json;
    $.getJSON('/cdnBuffet.json', function (data) {
        json = data;
        console.log(json); 
        myCallback(json); // this will return the data to the callback
                          //  specified by the use of the function
    });
}

这篇关于为什么在控制台中看不到此JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆