【发布时间】:2020-04-21 15:07:03
【问题描述】:
我一直坚持将信息翻译成对客户更友好的界面。以下是我从脚本中收到的 JSON 响应。但是,我想将其转换为您会在网站上看到的标准新闻提要。解决此问题的最佳方法是什么?
我希望在标题、摘要和 URL 链接旁边显示图像。
[
{
"datetime": 1545215400000,
"headline": "Voice Search Technology Creates A New Paradigm For Marketers",
"source": "Benzinga",
"url": "https://cloud.iexapis.com/stable/news/article/8348646549980454",
"summary": "<p>Voice search is likely to grow by leap and bounds, with technological advancements leading to better adoption and fueling the growth cycle, according to Lindsay Boyajian, <a href=\"http://loupventures.com/how-the-future-of-voice-search-affects-marketers-today/\">a guest contributor at Loup Ventu...",
"related": "AAPL,AMZN,GOOG,GOOGL,MSFT",
"image": "https://cloud.iexapis.com/stable/news/image/7594023985414148",
"lang": "en",
"hasPaywall": true
}
]
下面是我发起拉取的js。
function news() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var newsfeed = JSON.parse(this.responseText);
document.getElementById("news").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://cloud.iexapis.com/stable/stock/spy/news/last/1?token=pk_6925213461cb489b8c04a632e18c25dd", false);
xhttp.send();
};
我在我的 HTML 中使用它来显示原始 JSON,然后再处理成我想要的。
<div id=news class="text-white-50">
<script>
document.onreadystatechange = function() {
if (document.readyState === 'complete')
{
news();
}
};
</script>
</div>
【问题讨论】:
-
你能发布一些你尝试过的代码吗?此外,如果您从脚本中获取 json 响应,您可以使用 js 将数据附加到您的 html
-
在编辑中更新 - 在 Codepen 中显示:codepen.io/ethor11/pen/LYpGLEM
-
您将 responseText 解析为变量名称新闻源。所以不要使用
this.responseText,而是使用newsfeed[0]["headline"]来设置innerHTML