Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Trying to make 2 Ajax calls via JQuery, and then prepending the data

I'm working through the Freecodecamp Twitch API project and I'm unable to get the API data to display correct. The logo, channel and status comes back as undefined.

I know the API is working definitely. Must be something wrong in the way I've written in the code, but can't figure out what.

Here's my code:

$(document).ready(function() {

  var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

  for (i=0; i<users.length; i++) {
    var url="https://api.twitch.tv/kraken/channels/" + users[i];
    var logo;
    var channel;
    var status;
    $.ajax ({
      type: 'GET',
        url: url,
      headers: {
        'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
      },
      success: function(data) {
        logo = data.logo;
        channel = data.name;
      }      

    });
    var url2 = "https://api.twitch.tv/kraken/streams/" + users[i];
    $.ajax ({
      type: 'GET',
      url: url2,
      headers: {
        'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
      },
      success: function(data2) {
        if (data2.stream == null) {
          status = "Offline";
        } else {
          status = "Online";
        };

      }

    });
    $("#channelInfo").prepend("<div class='row'><div class='col-xs-4'><img src="+logo+"></div><div class='col-xs-4'>"+channel+"</div><div class='col-xs-4'>"+status+"</div>")

  };
});

Here's a link to my codepen: http://codepen.io/drhectapus/pen/VPNQJa?editors=1011

Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simply: an ajax call works like, you send a request and somewhat later(we do not know when!) a response would come.

if you have an AJAX call:

So you'd provide a function(){} and give it to your AJAX API ($ajax() in your case), and your Ajax API would run your function(){} when the response is received, so simple and nice. this is called an Asynchronous behaviour.

so if you wanna do something when your response is received you should code inside your function(){}.

If you have a bunch of AJAX calls:

The same rule applies here, but I assume you are gonna do something when all the responses of each ajax call are received. much work is needed.

let's say you have 3 ajax calls,

One way is to have one single function(){} for each of them like this:

$.ajax( "http://url_1.com", response );//say this response triggers 1sec later
$.ajax( "http://url_2.com", response );//say this response triggers 3sec later
$.ajax( "http://url_3.com", response );//say this response triggers 2sec later

Finally our response callback function would trigger 3 times if everything in network was OK.

var res = [];

function response(data) {
    // the data is handled by $.ajax() so every time I can ask for sent data like url, headers and etc.

    if (data.url == "http://url_1.com") {
        res[0] = data;
    }
    else if (data.url == "http://url_2.com") {
        res[1] = data;
    }
    else if(data.url == "http://url_3.com"){
        res[2] = data;
    }

    if(arr.length === 3){
    //we are done now, our array has 3 indexes and values
    //it means this is the third call(and last) of the response function
    }
}

so I defined an array called res and allocate each index for one specific URL.

But we are not done yet, Response function should know when all the array is filled, so need to check our array to make sure each index is filled.

all the code you see is deeply simplified and is for demonstration purpose, you need to provide much checking for production.

this scenario(bunch of ajax calls) can be done by other methods, like Promises or generators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...