如何将API中的JSON数据集成到HTML代码中?

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

How to integrate JSON data from API into html code?

问题

(noob问题),但我在使用从FAA NOTAM API接收的JSON数据并将其通过id或class转换为HTML代码时遇到了一些困难。

var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function(e) {
  var response = e.target.responseText;
  console.log(response);
});
xhr.addEventListener('error', function(e) {
  console.error('请求错误,状态为', e.target.status);
});
xhr.open('GET', 'https://external-api.faa.gov/notamapi/v1/notams?icaoLocation=ELLX');
xhr.setRequestHeader('client_id','');
xhr.setRequestHeader('client_secret','');
xhr.send();
<a id="input"></a>
英文:

(noob question), but I have some difficulties using the JSON data, I receive from the FAA NOTAM API and converting that via an id or class into html code.

(I have hidden the keys on purpose)

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

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

var xhr = new XMLHttpRequest();
xhr.addEventListener(&#39;load&#39;, function(e) {
  var response = e.target.responseText;
  console.log(response);
});
xhr.addEventListener(&#39;error&#39;, function(e) {
  console.error(&#39;Request error with status&#39;, e.target.status);
});
xhr.open(&#39;GET&#39;, &#39;https://external-api.faa.gov/notamapi/v1/notams?icaoLocation=ELLX&#39;);
xhr.setRequestHeader(&#39;client_id&#39;,&#39;&#39;);
xhr.setRequestHeader(&#39;client_secret&#39;,&#39;&#39;);
xhr.send();

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

&lt;a id=&quot;input&quot;&gt;&lt;/a&gt;

<!-- end snippet -->

答案1

得分: 1

我不建议在JavaScript中使用旧式的异步处理方式(XMLHTTPRequest),但在任何处理JavaScript中的异步方式时,当你从API获取响应时,你应该将JSON响应解析为DOM。你可以在how-to-call-for-json-output-from-an-api-into-html中找到关于如何执行这个操作的步骤。(链接的帖子使用fetch API来处理JavaScript中的异步操作)

而且,如果你是新手在处理JavaScript异步操作方面,how-do-i-return-the-response-from-an-asynchronous-call这个帖子有很好的解释关于处理JavaScript异步操作。

英文:

I don't recommend the old school way of asynchronous handling in js (XMLHTTPRequest) but in any way of handling asynchronous in js when you take response from api you should parse that json reponse to DOM. you can find your answer about steps of doing this in how-to-call-for-json-output-from-an-api-into-html.(linked post is using fetch api for handling asynchronous in js)

and also if you are new to asynchronous js, how-do-i-return-the-response-from-an-asynchronous-call this post have a good explanations of handling asynchronous js.

huangapple
  • 本文由 发表于 2023年2月24日 12:09:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552550.html
匿名

发表评论

匿名网友

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

确定