ajax调用完成后调用函数

时间:2016-06-02 03:59:01

标签: javascript jquery ajax

我正在尝试使用twitch.tv的api来获取有关某些频道的信息。我有所有不同的通道,我试图获取有关数组的信息,我用forloop迭代,在这个循环中我然后为这些通道中的每一个创建一个$ .ajax()。在我得到关于这些频道的信息之后,我将它们存储在一个对象中,然后我根据信息的不同推送到不同的阵列,当前频道正在流式传输或离线。我的问题似乎是,当我调用显示方法并将我的divs html更改为有关频道的信息时,一些请求尚未完成,因此我没有将所有频道添加到页面上。所以我的问题是我应该在哪里调用此代码中的显示功能,以及是否有更好的方法来实现我想要实现的目标。 在此先感谢这里是代码。 https://jsfiddle.net/bwsvxsdv/4/

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
    </head>
<body>
    <div class="well">
        <h1>Twitch.TV API</h1>

    </div>

    <div class="row">
        <div class="col-sm-3 text-center">
            Name
        </div>

        <div class="col-sm-9 text-center">
            Status
        </div>
    </div>

    <div class="channelContainer">

    </div>
    <script>
        $streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp",
        "storbeck", "habathcx", "RobotCaleb",
        "noobs2ninjas", "brunofin", "comster404","zxcxxxxzzxxxxc"];

        $onlineChannels = [];
        $offlineChannels = [];
        $closedChannels = [];
        $nonExistantChannels = [];

        function getStreamInfo(callback){
            for($i=0;$i<$streamers.length;$i++){
                $.ajax({
                    name:$streamers[$i],
                    length:$streamers.length-1,
                    index:$i,
                    func: callback,
                    url:'https://api.twitch.tv/kraken/streams/'+$streamers[$i],
                    dataType:'JSON',
                    success: function(data){

                        if(data.stream != null){//if there is stream information
                            //add to online channels
                            //console.log("its a streaming channel");
                            $chanInfo = {"name":this.name,"game":data.stream.game,"status":data.stream.channel.status};
                            $onlineChannels.push($chanInfo);
                        }else{
                            //add to offlineChannels
                            //console.log("currently not streaming");
                            $chanInfo = {"name":this.name,"status":"Offline"};
                            $offlineChannels.push($chanInfo);
                        }



                    },
                    error: function(data){
                        if(data.status === 422){
                            //console.log('add to closedChannels');
                            $chanInfo = {"name":this.name,"status":"Account closed"};
                            $closedChannels.push($chanInfo);
                        }

                        if(data.status === 404){
                            //console.log('add to nonExistantChannels');
                            $chanInfo = {"name":this.name,"status":"Non existant channel"};
                            $nonExistantChannels.push($chanInfo);
                        }
                    },//end of error                        
                    complete: function(){
                        if(this.index === this.length){
                            callback();
                        }
                    }
                });//end of ajax request

            }//end of for loop
        }//end of function

        function displayChannels(){
        console.log('doing displayChannels function');
        $chans = [$onlineChannels,$offlineChannels,$closedChannels];

        $html = "";
        for($i =0;$i<$onlineChannels.length;$i++){
            console.log("making the html");
            $html+= '<div class="row"><div class="col-sm-3 text-center">'+$onlineChannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$onlineChannels[$i]["status"]+'</div></div>'

        }
        for($i =0;$i<$offlineChannels.length;$i++){
            console.log("making the html");
            $html+= '<div class="row"><div class="col-sm-3 text-center">'+$offlineChannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$offlineChannels[$i]["status"]+'</div></div>'

        }
        for($i =0;$i<$closedChannels.length;$i++){
            console.log("making the html");
            $html+= '<div class="row"><div class="col-sm-3 text-center">'+$closedChannels[$i]["name"]+'</div><div class="col-sm-9 text-center">'+$closedChannels[$i]["status"]+'</div></div>'

        }
        console.log($html);
        console.log("about to add html");
        $(".channelContainer").html($html);
        console.log("html added");
        }

        getStreamInfo(displayChannels);
    </script>
</body>

3 个答案:

答案 0 :(得分:2)

您可以像这样使用Deferred数组,并在所有延迟对象都已解析后调用您的回调。

$streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp",
  "storbeck", "habathcx", "RobotCaleb",
  "noobs2ninjas", "brunofin", "comster404", "zxcxxxxzzxxxxc"
];

$onlineChannels = [];
$offlineChannels = [];
$closedChannels = [];
$nonExistantChannels = [];

function getStreamInfo() {
    var deferred = [];   // deferred array.
    for ($i = 0; $i < $streamers.length; $i++) {
      deferred.push(
        $.ajax({
          name: $streamers[$i],
          length: $streamers.length - 1,
          index: $i,

          url: 'https://api.twitch.tv/kraken/streams/' + $streamers[$i],
          dataType: 'JSON',
          success: function(data) {

            if (data.stream != null) { //if there is stream information
              //add to online channels
              //console.log("its a streaming channel");
              $chanInfo = {
                "name": this.name,
                "game": data.stream.game,
                "status": data.stream.channel.status
              };
              $onlineChannels.push($chanInfo);
            } else {
              //add to offlineChannels
              //console.log("currently not streaming");
              $chanInfo = {
                "name": this.name,
                "status": "Offline"
              };
              $offlineChannels.push($chanInfo);
            }



          },
          error: function(data) {
              if (data.status === 422) {
                //console.log('add to closedChannels');
                $chanInfo = {
                  "name": this.name,
                  "status": "Account closed"
                };
                $closedChannels.push($chanInfo);
              }

              if (data.status === 404) {
                //console.log('add to nonExistantChannels');
                $chanInfo = {
                  "name": this.name,
                  "status": "Non existant channel"
                };
                $nonExistantChannels.push($chanInfo);
              }
            } //end of error						

        }) //end of ajax request
      );





    } //end of for loop
    return deferred; // return the array
  } //end of function

function displayChannels() {
  console.log('doing displayChannels function');
  $chans = [$onlineChannels, $offlineChannels, $closedChannels];

  $html = "";
  for ($i = 0; $i < $onlineChannels.length; $i++) {
    console.log("making the html");
    $html += '<div class="row"><div class="col-sm-3 text-center">' + $onlineChannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $onlineChannels[$i]["status"] + '</div></div>'

  }
  for ($i = 0; $i < $offlineChannels.length; $i++) {
    console.log("making the html");
    $html += '<div class="row"><div class="col-sm-3 text-center">' + $offlineChannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $offlineChannels[$i]["status"] + '</div></div>'

  }
  for ($i = 0; $i < $closedChannels.length; $i++) {
    console.log("making the html");
    $html += '<div class="row"><div class="col-sm-3 text-center">' + $closedChannels[$i]["name"] + '</div><div class="col-sm-9 text-center">' + $closedChannels[$i]["status"] + '</div></div>'

  }
  console.log($html);
  console.log("about to add html");
  $(".channelContainer").html($html);
  console.log("html added");
}


var deferredArr = getStreamInfo();
// call your callback once all the ajax calls are done
$.when.apply(null, deferredArr).done(function() {
  alert("All requests completed!. Now calling displayChannels");
  displayChannels();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well">
  <h1>Twitch.TV API</h1>

</div>

<div class="row">
  <div class="col-sm-3 text-center">
    Name
  </div>

  <div class="col-sm-9 text-center">
    Status
  </div>
</div>

<div class="channelContainer">

</div>

答案 1 :(得分:0)

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
// NOTE:  This function must return the value 
//        from calling the $.ajax() method.
return $.ajax({
    url: "someUrl",
    dataType: "json",
    data:  yourJsonData,            
    ...
});
}

使用$ .when功能支持bu jquery

它像诺言一样工作。

希望这对你有用。

答案 2 :(得分:0)

我已经完成了代码,除了调用方法外似乎没问题。在你的方法中,当加载DIV时,一些请求信息不在你身边。

解决方案:在调用后调用显示方法并从API获取所有信息。为此,您可以使用“在回调时多个同时的ajax请求”,如下所示

code skeleton

让您的API调用在“when block”内部进行,然后在完成所有操作之后,您可以调用display方法将数据填充到视图层中

谢谢。