【问题标题】:$.getJSON example on callback function [duplicate]$.getJSON 回调函数示例
【发布时间】:2017-05-17 09:29:40
【问题描述】:

我想通过 $.getJSON 调用访问数据,并将其作为数组返回。我的数据已正确传输到我的回调函数,但在我调用函数时仍未定义。我哪里弄错了?谁能给我看一个使用 $.getJSON 的例子吗?

我的代码:

function countTypes( resource ) {
    $.getJSON( resource, otherFunction ); 
}

function otherFunction( data ) {
    var types = [];
    $.each(data, function( i, item ) {
        types.push( item['id'] );
    });
    console.log( types ); // This one works :)
    return types;
}

types = countTypes( 'my_resource' );  // types is undefined :(

【问题讨论】:

    标签: javascript json callback


    【解决方案1】:
    1. countTypes 不返回任何内容
    2. 类型获得值需要一段时间,而您无法控制它。因此,如果不检查是否为它分配了值,就不能使用类型。
    3. 您定义了变量“类型”两次。在 otherFunction 中定义它并使用“var”,这样它就不会覆盖外部的“类型”。但这仍然是不好的做法(在小代码 sn-ps 中)。尝试使用更好的命名方式。

    编辑: 2错了。对于那个很抱歉。您想要做的是创建一个处理类型的函数,就像您最初想要的那样(并且不在您的问题中)。

    var doSomethingWithTypes = function(types){
      $.each(types, function(index, type){
            console.log(type);
      });
    

    };

    现在,在 otherFunc 中,一旦您获得类型 - 调用 doSomethingWithTypes(types):

    function otherFunction( data ) {
        var types = [];
        $.each(data, function( i, item ) {
            types.push( item['id'] );
        });
        doSomethingWithTypes(types);
    }
    

    【讨论】:

    • 你能给我一个代码示例吗?
    • 编辑了我最初的答案(没有得到爱......)
    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2010-12-16
    • 2018-07-25
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多