在另一个API调用中进行一个API调用? [英] Make an API call inside of another API call?

查看:65
本文介绍了在另一个API调用中进行一个API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上需要合并来自两个不同API调用的数据.这是我现在所拥有的:

I basically need to combine data from two different API calls. Here is what I have right now:

    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
            }
        }
    });

上面的作品.

问题是我还需要来自 https://website.com/api2.json(将来自api1调用中的数据).我需要我的最终代码如下所示:

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('<tr><td><a href="'+api2[i].thing+'">+api[i].thing+'</a></td></tr>');

推荐答案

最简单的方法是在第一个API调用的成功回调中进行该API调用.可能看起来像这样:

Easiest way forward would be to make that API call in the success callback of your first API call. Might look something like:

var url= "https://website.com/api.json";
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {'X-API-Key': 'xxxxxx'},
    success: function(data){
      // now you have closure over results from api call one
      $.ajax({
        url: 'apiURL2', // or something
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': data.results.apiKey // or something },
        success: function(moreData){

        var api = data.results[0].api;

        for (var i=0;i<api.length;++i)
        {
            $('tbody').append('<tr><td>'+api[i].thing+ moreData.thing'</td></tr>');
        }
    }
  })
});

这篇关于在另一个API调用中进行一个API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆