简体   繁体   English

jQuery:多个getJSON请求,第二个不起作用

[英]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: 我有一个Javascript / JQuery脚本,它向不同的API发出多个getJSON请求,如下所示:

  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? 为什么第二个getJSON不显示值? Is there a rule I do not know about affecting the results of my code? 我有不了解影响代码结果的规则吗?

$.getJSON is an asynchronous call. $.getJSON是一个异步调用。 You should do something like this instead: 您应该改为执行以下操作:

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

When you do $('h1').text(BTC_Value); 当您执行$('h1').text(BTC_Value); BTC_Value doesn't have the value you want yet. BTC_Value还没有您想要的值。 When the AJAX request completets it does, but not before. 当AJAX请求完成时,它会完成,但不会在此之前完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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