循环中的jQuery ajax

时间:2016-02-03 22:47:45

标签: javascript jquery ajax

我有两个函数都进行jQuery调用,第一个获取冠军ID,第二个使用ID获取冠军名称,现在我有10个冠军名称,所以我使用for循环但它不会起作用...
这是我的代码:

function GetChampName(id) {
  $.ajax({
    url: 'https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' + id + '?api_key=f8453a98-ad2c-455e-b9df-f46c4f99d0ed',
    datatype: 'json',
    type: 'get',
    success: function(json) {
      sName = json.name;
    }
  });
  return sName;
}

function summonerLookUp() {
  var cn = [];
  $.ajax({
    url: 'https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/46743451/recent?api_key=f8453a98-ad2c-455e-b9df-f46c4f99d0ed',
    datatype: 'json',
    type: 'get',
    success: function(json) {
      for (var i = 0; i <= json.games.length; i++) {
        var id = json.games[i].championId;
        $('#t1 tr:last').after('<tr> <td>' + json.games[i].gameId + '</td><td id="e">' + cn[i] + '</td><td>' + wl(json.games[i].stats.win) + '</td> </tr>');
      }
    }
  });
}

1 个答案:

答案 0 :(得分:-1)

function GetChampName(id,cb) {
  $.ajax({
    url: 'https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' + id + '?api_key=f8453a98-ad2c-455e-b9df-f46c4f99d0ed',
    datatype: 'json',
    type: 'get',
    success: function(json) {
      sName = json.name;
      cb(sName)
    }
  });
}

function summonerLookUp() {
  $.ajax({
    url: 'https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/46743451/recent?api_key=f8453a98-ad2c-455e-b9df-f46c4f99d0ed',
    datatype: 'json',
    type: 'get',
    success: function(json) {
      for (var i = 0; i <= json.games.length; i++) {
        if(json.games[i]){
          var id = json.games[i].championId;
          GetChampName(id,function(sName){
            console.log(sName);
            var html = '<tr> <td>';
            html += json.games[i].gameId;
            html += '</td><td id="e">' + sName + '</td><td>';
            html += wl(json.games[i].stats.win);
            html += '</td> </tr>';
            $('#t1 tr:last').after(html);
          });
        }
      }
    }
  });
}

summonerLookUp();