2016-06-02 12 views
2

Ich versuche Twitch.tv API zu verwenden, um Informationen über einige Kanäle zu erhalten. Ich habe alle verschiedenen Kanäle im Versuch, Informationen in einem Array zu erhalten, die ich mit einem Forloop durchlaufen und innerhalb dieser Schleife mache ich dann eine $ .ajax() für jeden dieser Kanäle. Nachdem ich die Informationen erhalten habe, die ich über diese Kanäle möchte, speichere ich sie in einem Objekt, das ich dann auf verschiedene Arrays drücke, abhängig davon, ob der Kanal gerade streamt oder offline ist. Mein Problem scheint zu sein, dass, wenn ich die Anzeige-Methode anrufe und meine divs html zu den Informationen über die Kanäle ändere, einige der Anfragen noch nicht abgeschlossen sind und aus diesem Grund bekomme ich nicht alle Kanäle auf der Seite hinzugefügt. Also meine Frage ist, wo sollte ich die Display-Funktion in diesem Code und wenn es einen besseren Ansatz zu was ich versuche zu erreichen. Vielen Dank im Voraus hier ist der Code. https://jsfiddle.net/bwsvxsdv/4/Anruf-Funktion nach Ajax-Anrufe beendet haben

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

Was ist name: $ Streamer [$ i], Länge: $ Streamer.Length-1, Index: $ i, Func: Rückruf, in der Ajax? Neben jeder Schleife verwenden Sie $ i. Willst du, dass $ i eine globale Variable ist? – brk

+0

@ user2181397 Das ist nur der Name des Streamers, der gerade mit einer For-Schleife beschäftigt ist, die alle Streamer durchläuft. – mjmendes

+0

Welche Ajax-Eigenschaften sind diese 'name: $ streamers [$ i], length: $ streamers. Länge - 1, Index: $ i, '? – madalinivascu

Antwort

2

können Sie Deferred Array verwenden wie so und Ihr Rückruf anrufen, wenn alle aktivierten Objekte wurden gelöst.

$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,    
    ... 
}); 
} 

Verwendung $ .when Funktionalität unterstützt bu jquery

es ist wie Versprechen zu arbeiten.

hoffe, das wird für Sie arbeiten.

0

Ich habe den Code durchlaufen und es scheint gut, außer dem Aufruf approach.In Ihrem Ansatz ist die einige der Anforderungsinformationen nicht mit Ihnen, wenn das DIV geladen ist.

Lösung: die Anzeigemethode nach Anruf Rufen und alle Informationen aus dem API.To bekommen Sie es können Sie „Mehrere gleichzeitige AJAX-Anfragen in zu Callback“ verwenden als

Anrufe

code skeleton

machen Ihre API folgt passiert innerhalb der "Wenn Block" und dann nach Abschluss alle dann können Sie die Anzeige-Methode, um Ihre Daten in die Ansicht Schicht

Vielen Dank.

Verwandte Themen