使用HTML和JavaScript中的Fetch API从API获取数据

huangapple go评论108阅读模式
英文:

Fetching data from an API using the Fetch API in HTML with JavaScript

问题

I'm here to provide you with the translated code portion. Here's the code you provided in Chinese:

嘿,我正在努力获取一个API。我就是无法让它工作。

<!DOCTYPE html>
<html>
<head>
  <title>Sponsorkliks API Table</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      padding: 8px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
  <table id="api-table">
    <thead>
      <tr>
        <th>名称</th>
        <th>网址</th>
        <th>标志</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>

  <script>
    fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension')
      .then(response => response.json())
      .then(data => {
        const tableBody = document.querySelector('#api-table tbody');
        data.forEach(item => {
          const row = document.createElement('tr');
          const nameCell = document.createElement('td');
          nameCell.textContent = item.name;
          row.appendChild(nameCell);
          const urlCell = document.createElement('td');
          const urlLink = document.createElement('a');
          urlLink.href = item.url;
          urlLink.textContent = item.url;
          urlCell.appendChild(urlLink);
          row.appendChild(urlCell);
          const logoCell = document.createElement('td');
          const logoImg = document.createElement('img');
          logoImg.src = item.logo;
          logoImg.alt = item.name;
          logoImg.style.maxWidth = '100px'; // 根据需要调整大小
          logoCell.appendChild(logoImg);
          row.appendChild(logoCell);
          tableBody.appendChild(row);
        });
      })
      .catch(error => console.error(error));
  </script>
</body>
</html>

If you have any further questions or need assistance with specific parts of the code, feel free to ask.

英文:

Hey I am struggling to fetch an API. I just don't get it to work.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Sponsorkliks API Table&lt;/title&gt;
&lt;style&gt;
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table id=&quot;api-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;URL&lt;/th&gt;
&lt;th&gt;Logo&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;
&lt;script&gt;
fetch(&#39;https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension&#39;)
.then(response =&gt; response.json())
.then(data =&gt; {
const tableBody = document.querySelector(&#39;#api-table tbody&#39;);
data.forEach(item =&gt; {
const row = document.createElement(&#39;tr&#39;);
const nameCell = document.createElement(&#39;td&#39;);
nameCell.textContent = item.name;
row.appendChild(nameCell);
const urlCell = document.createElement(&#39;td&#39;);
const urlLink = document.createElement(&#39;a&#39;);
urlLink.href = item.url;
urlLink.textContent = item.url;
urlCell.appendChild(urlLink);
row.appendChild(urlCell);
const logoCell = document.createElement(&#39;td&#39;);
const logoImg = document.createElement(&#39;img&#39;);
logoImg.src = item.logo;
logoImg.alt = item.name;
logoImg.style.maxWidth = &#39;100px&#39;; // adjust size if needed
logoCell.appendChild(logoImg);
row.appendChild(logoCell);
tableBody.appendChild(row);
});
})
.catch(error =&gt; console.error(error));
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

I would like to use the API above and would like to take data out if it. However, everything I tried so far did not work.

I tried a lot of different things to fetch the data. I have nevert worked with this before, so I can not figure it out.

答案1

得分: 2

你只是不太专注于你的数据。你应该迭代 data.webshops 并在 webshop 对象中使用不同的字段名称:

fetch('https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension')
  .then(response => response.json())
  .then(({webshops}) => {
    const tableBody = document.querySelector('#api-table tbody');
    webshops.forEach(item => {
      const row = document.createElement('tr');
      const nameCell = document.createElement('td');
      nameCell.textContent = item.name_short;
      row.appendChild(nameCell);
      const urlCell = document.createElement('td');
      const urlLink = document.createElement('a');
      urlLink.href = item.link;
      urlLink.textContent = item.orig_url;
      urlCell.appendChild(urlLink);
      row.appendChild(urlCell);
      const logoCell = document.createElement('td');
      const logoImg = document.createElement('img');
      logoImg.src = item.logo_120x60;
      logoImg.alt = item.name_short;
      logoImg.style.maxWidth = '100px'; // 根据需要调整大小
      logoCell.appendChild(logoImg);
      row.appendChild(logoCell);
      tableBody.appendChild(row);
    });
  })
  .catch(error => console.error(error));

我也不建议使用 DOM 添加元素,它速度较慢,可以使用纯 HTML:

fetch('https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension')
  .then(response => response.json())
  .then(({webshops}) => {
    document.querySelector('#api-table tbody').innerHTML = 
      webshops.map(item => 
      `<tr>
        <td>${item.name_short}</td>
        <td><a href="${item.link}">${item.orig_url}</a></td>
        <td>
          <img src="${item.logo_120x60}" 
            style="max-width:100px"
            alt="${item.name_short}">
        </td>
      </tr>`
      ).join('')
  })
  .catch(error => console.error(error));

希望这些代码对你有所帮助。

英文:

You're just not so focused on your data. You should iterate data.webshops and use different field names in a webshop object:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    fetch(&#39;https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension&#39;)
.then(response =&gt; response.json())
.then(({webshops}) =&gt; {
const tableBody = document.querySelector(&#39;#api-table tbody&#39;);
webshops.forEach(item =&gt; {
const row = document.createElement(&#39;tr&#39;);
const nameCell = document.createElement(&#39;td&#39;);
nameCell.textContent = item.name_short;
row.appendChild(nameCell);
const urlCell = document.createElement(&#39;td&#39;);
const urlLink = document.createElement(&#39;a&#39;);
urlLink.href = item.link;
urlLink.textContent = item.orig_url;
urlCell.appendChild(urlLink);
row.appendChild(urlCell);
const logoCell = document.createElement(&#39;td&#39;);
const logoImg = document.createElement(&#39;img&#39;);
logoImg.src = item.logo_120x60;
logoImg.alt = item.name_short;
logoImg.style.maxWidth = &#39;100px&#39;; // adjust size if needed
logoCell.appendChild(logoImg);
row.appendChild(logoCell);
tableBody.appendChild(row);
});
})
.catch(error =&gt; console.error(error));

<!-- language: lang-css -->

    table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}

<!-- language: lang-html -->

  &lt;table id=&quot;api-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;URL&lt;/th&gt;
&lt;th&gt;Logo&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;

<!-- end snippet -->

I also don't recommend adding elements with DOM, it's slow, use pure html:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

fetch(&#39;https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension&#39;)
.then(response =&gt; response.json())
.then(({webshops}) =&gt; {
document.querySelector(&#39;#api-table tbody&#39;).innerHTML = 
webshops.map(item =&gt; 
`&lt;tr&gt;
&lt;td&gt;${item.name_short}&lt;/td&gt;
&lt;td&gt;&lt;a href=&quot;${item.link}&quot;&gt;${item.orig_url}&lt;/td&gt;
&lt;td&gt;
&lt;img src=&quot;${item.logo_120x60}&quot; 
style=&quot;max-width:100px&quot;
alt=&quot;${item.name_short}&quot;&gt;
&lt;/td&gt;
&lt;/tr&gt;`
).join(&#39;&#39;)
})
.catch(error =&gt; console.error(error));

<!-- language: lang-css -->

table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}

<!-- language: lang-html -->

&lt;table id=&quot;api-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;URL&lt;/th&gt;
&lt;th&gt;Logo&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;

<!-- end snippet -->

答案2

得分: 0

问题是数据应该是一个数组,但实际上是一个 Object {webshops: Array(694)}。将 data.foreach(item =&gt; { 更改为 Object.values(item =&gt; {。然后,循环遍历对象内的每个数组并提取数据。然而,在这个过程中,我意识到对象的形式是 Object {category: &quot;Gifts&quot;, name_short: &quot;Sinterklaas-feestwinkel.nl&quot;, name_long: &quot;Sinterklaas-feestwinkel.nl&quot;, description: &quot;De Sinterklaas-feestwinkel.nl is er voor alle Sinterklaas inkopen, naast een grote assortiment Sinterklaas versiering en Sinterklaas en Zwarte pieten kostuums heeft deze winkel ook kado’s voor jong en oud. Hier vindt men alles voor een geslaagde Sinterklaas avond.&quot;, logo_120x60: &quot;https://www.sponsorkliks.com/gfx/partners/sinterklaas-feestwinkel.png&quot;, …},所以我认为你在写 URL 时出错了。我将其替换为 'description',如下所示:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Sponsorkliks API Table&lt;/title&gt;
  &lt;style&gt;
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      padding: 8px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }
    th {
      background-color: #f2f2f2;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;table id=&quot;api-table&quot;&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Name&lt;/th&gt;
        &lt;th&gt;Description&lt;/th&gt;
        &lt;th&gt;Logo&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;&lt;/tbody&gt;
  &lt;/table&gt;

  &lt;script&gt;
    fetch(&#39;https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension&#39;)
      .then(response =&gt; response.json())
      .then(data =&gt; {
        const tableBody = document.querySelector(&#39;#api-table tbody&#39;);
        Object.values(data).forEach(item =&gt; {
          item.forEach((item) =&gt; {
            const row = document.createElement(&#39;tr&#39;);
            const nameCell = document.createElement(&#39;td&#39;);
            nameCell.textContent = item.name_short;
            row.appendChild(nameCell);
            const descriptionCell = document.createElement(&#39;td&#39;);
            const description = document.createElement(&#39;div&#39;);
            description.innerHTML = item.description;
            descriptionCell.appendChild(description);
            row.appendChild(descriptionCell);
            const logoCell = document.createElement(&#39;td&#39;);
            const logoImg = document.createElement(&#39;img&#39;);
            logoImg.src = item.logo_120x60;
            logoImg.alt = item.name_short;
            logoImg.style.maxWidth = &#39;100px&#39;; // 调整大小,如果需要的话
            logoCell.appendChild(logoImg);
            row.appendChild(logoCell);
            tableBody.appendChild(row);
          });
        });
      })
      .catch(error =&gt; console.error(error));
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

但要注意,由于我禁用了脚本转义,所以如果 API 中有一个隐藏的 &lt;script&gt; 标签,它将运行,可能导致代码注入攻击。

英文:

The problem is that data is supposed to be an array, but instead is an Object {webshops: Array(694)}. Change data.foreach(item =&gt; { to Object.values(item =&gt; {. Then, loop through each of the arrays inside of the object and grab the data. However, while doing this, a I realized the objects take the form of Object {category: &quot;Gifts&quot;, name_short: &quot;Sinterklaas-feestwinkel.nl&quot;, name_long: &quot;Sinterklaas-feestwinkel.nl&quot;, description: &quot;De Sinterklaas-feestwinkel.nl is er voor alle Sinterklaas inkopen, naast een grote assortiment Sinterklaas versiering en Sinterklaas en Zwarte pieten kostuums heeft deze winkel ook kado’s voor jong en oud. Hier vindt men alles voor een geslaagde Sinterklaas avond.&quot;, logo_120x60: &quot;https://www.sponsorkliks.com/gfx/partners/sinterklaas-feestwinkel.png&quot;, …}, so I think you were mistaken when you wrote url. Instead of url, I swapped it out for 'description', as shown below:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Sponsorkliks API Table&lt;/title&gt;
&lt;style&gt;
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table id=&quot;api-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;th&gt;Logo&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;
&lt;script&gt;
fetch(&#39;https://www.sponsorkliks.com/api/?club=11592&amp;call=webshops_club_extension&#39;)
.then(response =&gt; response.json())
.then(data =&gt; {
const tableBody = document.querySelector(&#39;#api-table tbody&#39;);
Object.values(data).forEach(item =&gt; {
item.forEach((item) =&gt; {
const row = document.createElement(&#39;tr&#39;);
const nameCell = document.createElement(&#39;td&#39;);
nameCell.textContent = item.name_short;
row.appendChild(nameCell);
const descriptionCell = document.createElement(&#39;td&#39;);
const description = document.createElement(&#39;div&#39;);
description.innerHTML = item.description;
descriptionCell.appendChild(description);
row.appendChild(descriptionCell);
const logoCell = document.createElement(&#39;td&#39;);
const logoImg = document.createElement(&#39;img&#39;);
logoImg.src = item.logo_120x60;
logoImg.alt = item.name_short;
logoImg.style.maxWidth = &#39;100px&#39;; // adjust size if needed
logoCell.appendChild(logoImg);
row.appendChild(logoCell);
tableBody.appendChild(row);
});
});
})
.catch(error =&gt; console.error(error));
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

However, watch out, since I disabled script escaping, so if the api has a hidden &lt;script&gt; tag, it would run and this would result in a code injection attack.

huangapple
  • 本文由 发表于 2023年6月5日 01:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定