jQuery/ajax - 两个单独的 API 请求合并结果

jQuery/ajax - two separate API requests with combined results

晚上的互联网世界,

首先post这里要温柔点,到目前为止我从这个网站学到了很多东西..现在我寻求帮助..

我已经尝试了一些代码变体,例如 $when 和 $then,函数中的函数,但我无法得到我想要的结果,它没有合并结果。所以想最好在这里问一下并显示我的代码..请帮助..

html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="row" id="stats">
  <div class="col-4 col-12-large">
    <h4><strong>Ether contributed</strong></h4>
    <span id="eth_balance" style="font-size: 2.5em;">&mdash;</span>
    <!--<p id="total-ether-message" style="font-size:11px;"></p>-->
  </div>
  <div class="col-4 col-12-large">
    <h4><strong>Contributions in USD</strong></h4>
    <span id="token_usd" style="font-size: 2.5em;">&mdash;</span>
    <!--<p id="total-usd-message" style="font-size:11px;"></p>-->
  </div>
  <div class="col-4 col-12-large">
    <h4><strong>Tokens issued</strong></h4>
    <span id="token_amount" style="font-size: 2.5em;">&mdash;</span>
    <!-- <p id="total-tokens-message" style="font-size:11px;"></p> -->
  </div>
</div>

js

var token = '0xa74476443119A942dE498590Fe1f2454d7D4aC0d';
var address = '0xda0aed568d9a2dbdcbafc1576fedc633d28eee9a';

$.get("https://api.tokenbalance.com/token/" + token + "/" + address +'', function(data) {
    $("#eth_balance").html(Math.round(data.eth_balance).toFixed(2) + " ETH");
    $("#token_amount").html(Math.round(data.balance).toFixed(2) + " " + data.symbol);
});

$.get("https://api.etherscan.io/api?module=stats&action=ethprice", function(data) {
    $("#token_usd").html("$ " + Math.round(data.result.ethusd).toFixed(2));
    // Ideally I'd like to get [ data.result.ethusd x data.eth_balance ] to replace #token_usd, all wrapped in one function
    alert(data.result.ethusd)
});

或者你可以在这里玩

https://jsfiddle.net/4zwvo90n/8/

您可以将第二个 ajax 调用移到第一个调用中,并将 data 中的值存储在内部函数也可用的变量中。

像这样(第二次调用在这里或 fiddle 中不起作用):

    var token = '0xa74476443119A942dE498590Fe1f2454d7D4aC0d';
    var address = '0xda0aed568d9a2dbdcbafc1576fedc633d28eee9a';

    $.get("https://api.tokenbalance.com/token/" + token + "/" + address + '', function (data) {
        var eth_balance = data.eth_balance;
        $("#eth_balance").html(Math.round(data.eth_balance).toFixed(2) + " ETH");
        $("#token_amount").html(Math.round(data.balance).toFixed(2) + " " + data.symbol);
        $.get("https://api.etherscan.io/api?module=stats&action=ethprice", function (data) {
            $("#token_usd").html("$ " + Math.round(data.result.ethusd * eth_balance).toFixed(2));
            // Ideally I'd like to get [ data.result.ethusd x data.eth_balance ] to replace #token_usd, all wrapped in one function
            alert(data.result.ethusd)
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="row" id="stats">
    <div class="col-4 col-12-large">
        <h4>
            <strong>Ether contributed</strong>
        </h4>
        <span id="eth_balance" style="font-size: 2.5em;">&mdash;</span>
        <!--<p id="total-ether-message" style="font-size:11px;"></p>-->
    </div>
    <div class="col-4 col-12-large">
        <h4>
            <strong>Contributions in USD</strong>
        </h4>
        <span id="token_usd" style="font-size: 2.5em;">&mdash;</span>
        <!--<p id="total-usd-message" style="font-size:11px;"></p>-->
    </div>
    <div class="col-4 col-12-large">
        <h4>
            <strong>Tokens issued</strong>
        </h4>
        <span id="token_amount" style="font-size: 2.5em;">&mdash;</span>
        <!-- <p id="total-tokens-message" style="font-size:11px;"></p> -->
    </div>
</div>

听起来您要查找的是 Promise.all()(原版 JavaScript)或 $.when()(jQuery)。

这是更新后的 jQuery fiddle:https://jsfiddle.net/j5L54100/10/

一个可用的香草版本:https://jsfiddle.net/6Lwo7rs4/8/

在jQuery中:

var promise1 = $.get("https://api.tokenbalance.com/token/" + token + "/" + address);
var promise2 = $.get("https://api.etherscan.io/api?module=stats&action=ethprice");

$.when(promise1, promise2).then(function(p1Data, p2Data) {
  // do stuff with the data
}).catch(function (error) {
  // error handling
});

Vanilla JS(注意,像这样使用 JSON 你还需要 response.json(),参见 fiddle 和 https://developer.mozilla.org/en-US/docs/Web/API/Body/json):

var promise1 = fetch("https://api.tokenbalance.com/token/" + token + "/" + address);
var promise2 = fetch("https://api.etherscan.io/api?module=stats&action=ethprice");

Promise.all([promise1, promise2]).then(function(combinedData) {
  // do stuff with the data
}).catch(function (error) {
  // error handling
});

基本上发生的事情是 $.getfetch return 承诺(表示异步操作状态的对象,带有回调以处理不同的响应,例如 successfailure)。 when/all 本身就是一个 promise,等待它给出的所有 promise 的实现或者第一个 promise 失败。如果它给出的承诺成功,它会调用 then 函数。如果其中一个承诺失败,它会调用 catch 函数。

另一种选择是链接请求:

var url1 = "https://api.tokenbalance.com/token/" + token + "/" + address;
var url2 = "https://api.etherscan.io/api?module=stats&action=ethprice";

fetch(url1)
  .then(function(data1) {
    return fetch(url2);
  })
  .then(function(data2) {
    // do stuff with data1 and data2
  })
  .catch(function (error) {
    // handle errors
  });

在 ES6 中看起来很棒:

const url1 = `https://api.tokenbalance.com/token/${token}/${address}`;
const url2 = 'https://api.etherscan.io/api?module=stats&action=ethprice';

fetch(url1)
  .then(data1 => fetch(url2))
  .then(data2 => /* do stuff with data1 and data2 */)
  .catch(error => /* handle errors */);

Promise 超级棒,也很让人迷惑。我建议在进一步研究 promises 之前查看 fetch 的资源以了解总体思路。

获取:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

承诺:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Promise.all(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

jQuery.when(): https://api.jquery.com/jquery.when/