简体   繁体   English

从函数中检索变量

[英]Retrieving a variable from within a function

I am attempting to pull information from the League of Legends API. 我试图从英雄联盟API中提取信息。

To simplify what I am doing, I am attempting to pull information about a user and their previous matches. 为了简化我正在做的事情,我试图提取有关用户及其之前匹配的信息。 The problem that I run into is that when I parse a JSON request, it returns a champion ID rather than their name (Ex: 412 rather than "Thresh"). 我遇到的问题是,当我解析JSON请求时,它返回一个冠军ID而不是他们的名字(例如:412而不是“Thresh”)。

The only solution I can see for this would be to make another JSON request and parse that data for the champion name. 我能看到的唯一解决方案是发出另一个JSON请求并解析冠军名称的数据。 Currently what I have looks like this. 目前我看起来像这样。

$.getJSON(championMasteryPHP, function (json) {
    for (var i = 0; i < 20; i++) {
        var champID = json[i].championId;
        var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;

    $.getJSON(championInfo, function (json2) {
        var champName = json2.name;
    });

    $('#champ').append("<li>"+champID+" - "+champName+"</li>")
    }
});

I'm unable to access the champName variable due to it being nested within the second JSON function. 我无法访问champName变量,因为它嵌套在第二个JSON函数中。

Is there a better way to do this? 有一个更好的方法吗?

$.getJSON(championMasteryPHP, function (json) {
    for (var i = 0; i < 20; i++) {
        var champID = json[i].championId;
        var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;

    $.getJSON(championInfo, function (json2) {
        var champName = json2.name;
        $('#champ').append("<li>"+champID+" - "+champName+"</li>")
    });
    }
});

Just put it inside the second json request since you need to wait till that request is done anyway. 只需将它放在第二个json请求中,因为您需要等到该请求完成。

You should put the append statement in the callback because getJSON is an asynchronous method (does mean the Request is running in the background, and calls your function back when it got a response), so you should wait for the response first then you can append it to #champ : 你应该把append语句放在回调中,因为getJSON是一个异步方法(确实意味着Request在后台运行,并在得到响应时调用你的函数),所以你应该先等待响应,然后才能追加#champ

$.getJSON(championMasteryPHP, function (json) {
    for (var i = 0; i < 20; i++) {
        var champID = json[i].championId;
        var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;

        $.getJSON(championInfo, function (json2) {
             var champName = json.name;

             $('#champ').append("<li>"+champID+" - "+champName+"</li>")
        });

    }
});

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM