如何通过1次调用从不同对象获取信息? [英] How to get information from different objects with 1 call?

查看:75
本文介绍了如何通过1次调用从不同对象获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具有3个字段的标签列表:

I need to have list of tags with 3 fields:

  1. 标签名

  1. tag_name

tag_description

tag_description

计数器的帖子.

由于counter_of_posts是标记对象的字段,而tag_description(摘录)是tag_wiki的字段,如何通过一次调用获得所需的信息?

Since counter_of_posts is a field of tag-object and tag_description (excerpt) is a field of tag_wiki, how can I get needed information with one call?

推荐答案

这是不可能的-您至少需要2次通话(如果您有超过20个标签,则需要更多通话).一次调用/tags/{tags}/info?site={site}获取标签名称(已给出)和计数器,一次调用/tags/{tags}/wikis?site={site}.当然,您可以应用所需的任何过滤器并更改站点名称和标记名称.这是一个JavaScript示例:

This is impossible - you need at least 2 calls (more if you have more than 20 tags). One call to /tags/{tags}/info?site={site} to get the tag's name (which is given) and the counter and one to /tags/{tags}/wikis?site={site}. Of course, you can apply whatever filters you want and change the sitename and tag names. Here's a JavaScript sample:

(async function() {
  const key = '3loXx7CAr2AvrMaHBj6GxQ(('; // not necessary, but it increases daily API quota from 300 to 10000
  const sitename = 'stackoverflow'; // default, change it to whatever you want
  const tags = 'php;javascript;java;jquery;perl;python'; // semicolon-separated, must be =<20
  const tagApiUrl = 'https://api.stackexchange.com/2.2/tags/';
  const tagInfoFilter = '!-.G.68pp778y';
  const tagWikisFilter = '!*Ly1)NvM)n91RtK*';

  // First API call: get tag's info
  const callTagInfo = await fetch(`${tagApiUrl}${tags}/info?site=${sitename}&filter=${tagInfoFilter}&key=${key}`);
  const data_counter = await callTagInfo.json();

  // Second API call: get tag's excerpt
  const callTagWikis = await fetch(`${tagApiUrl}${tags}/wikis?site=${sitename}&filter=${tagWikisFilter}&key=${key}`);
  const data_excerpt = await callTagWikis.json();

  for (let i = 0; i < data_counter.items.length; i++) {
    const table = document.querySelector('table');
    const html = `
      <tr>
        <td>${data_counter.items[i].name}</td>
        <td>${data_excerpt.items.find(name => name.tag_name === data_counter.items[i].name).excerpt}</td>
        <td>${data_counter.items[i].count}</td>
      </tr>`;
     table.insertAdjacentHTML('beforeend', html);
  }
  console.log('API Quota remaining:', data_excerpt.quota_remaining);
})();

<link rel="stylesheet" href="https://unpkg.com/@stackoverflow/stacks/dist/css/stacks.min.css">
<table class="s-table">
  <tbody>
    <tr>
      <th>Tag Name</th>
      <th>Excerpt</th>
      <th>Number of posts</th>
    </tr>
  </tbody>
</table>

这篇关于如何通过1次调用从不同对象获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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