简体   繁体   中英

JQuery: Multiple getJSON requests, second does not work

I have a Javascript/JQuery script that makes multiple getJSON requests to different APIs, which goes something like this:

  var BTC_Value = 0;
  var LTC_Value = 0;

  var loadCoinValues = function()
  {
      $.getJSON( "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast", function( info ) {
       BTC_Value = info.data['last_local']['value'];
      });

      $.getJSON( "https://btc-e.com/api/2/ltc_usd/ticker", function( info ) {
       LTC_Value = info.ticker['avg'];
      });
     };

  loadCoinValues();

  $("h1").text(BTC_Value); //This returns the correct value.
  $("h2").text(LTC_Value); //This returns nothing.

Why does the second getJSON not display a value? Is there a rule I do not know about affecting the results of my code?

$.getJSON is an asynchronous call. You should do something like this instead:

$.getJSON(... ,function(info) {
  $('h1').text(info.data['last_local']['value']);
});

When you do $('h1').text(BTC_Value); BTC_Value doesn't have the value you want yet. When the AJAX request completets it does, but not before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM