2016-06-02 30 views
2

twitch.tvのapiを使用していくつかのチャンネルに関する情報を取得しようとしています。私はすべての異なるチャンネルを持っていますが、私はforループを使って繰り返し、このループの中でこれらのチャンネルのそれぞれに対して$ .ajax()を作ります。私はこれらのチャンネルについて私が必要とする情報を得た後、私はオブジェクトに格納します。そして、チャンネルに応じて異なる配列にプッシュします。チャンネルは現在ストリーミングまたはオフラインです。私の問題は、表示メソッドを呼び出し、チャンネルに関する情報にdivs htmlを変更すると、リクエストのいくつかがまだ完了していないため、この理由でページにすべてのチャンネルが追加されないということです。だから私の質問は、私はこのコードで表示関数を呼び出す必要があり、実現しようとしているものにもっと良いアプローチがあるかどうかです。 ここにコードをお寄せいただきありがとうございます。 https://jsfiddle.net/bwsvxsdv/4/ajax呼び出しが終了した後の呼び出し関数

<!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> 

+0

名前は何ですか:$ streamers [$ i]、長さ:$ streamers.length-1、インデックス:$ i、func:コールバック、ajax?あなたは$ iを使用しているすべてのループの横にあります。 $ iをグローバル変数にしますか? – brk

+0

@ user2181397これは、現在、すべての異なるストリーマを通過するためにforループを使用して現在imに忙しいストリーマの名前です。 – mjmendes

+0

ajaxプロパティは、これらの 'name:$ streamers [$ i]、 length:$ streamersです。長さ - 1、 インデックス:$ i、 '? – madalinivascu

答えて

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 \t \t \t \t \t \t 
 

 
     }) //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>

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の

それは約束のように働いています。

これはあなたのために働くことを望みます。

0

私はコードを通過しており、あなたのアプローチでは、DIVがロードされているときにあなたのアプローチのいくつかの要求情報はあなたとは別のアプローチで呼び出されます。

ソリューション:あなたのAPIの呼び出しを行う

code skeleton

を次のように、それはあなたが「コールバックの中に複数の同時AJAXリクエスト」を使用することができますコール後の表示方法を呼び出し、API.Toからすべての情報を取得しますブロック内で発生し、すべて完了したら表示メソッドを呼び出してビューレイヤにデータを移入することができます

ありがとうございます。

関連する問題