【问题标题】:how to parse data in javascript如何在javascript中解析数据
【发布时间】:2023-03-26 08:07:02
【问题描述】:

使用免费的 REST API:https://jsonplaceholder.typicode.com/ 获取 100张专辑。并将html页面上的所有专辑显示为:

 UserId: value of userId from the object that came to you,
 Id: Id value from the object that came to you,
 Title: title value from the object that came to you
 As a result, 100 different albums should be parsed on your page.

我尝试解析数据,数据变成了使用 JSON.parse() 的 JavaScript 对象,但数据以 json 格式显示

<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
 const xhttp = new XMLHttpRequest();
 const url = "https://jsonplaceholder.typicode.com/albums";
 xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML =
     this.responseText;
   }
 };

 xhttp.open("GET", url, true);
 xhttp.send();
}
</script>

【问题讨论】:

  • 那么错误是什么?如果 JSON.parse() 抛出错误听起来像是无效的 JSON。
  • 我添加 JSON.parse(.....) 它不起作用
  • 我试过你的代码并且 JSON.parse 工作。 var obj = JSON.parse(this.responseText); console.log(obj) 所以不确定你做错了什么。做一个显示错误的例子。在控制台中查找错误。
  • 它在 console.log() 中工作,但在 html 页面中它不起作用
  • 什么不起作用?它打印[object Object] 吗?

标签: javascript json jsonparser


【解决方案1】:

如果你添加一个&lt;div id="demo"&gt;&lt;/div&gt;,它就可以正常工作:

function loadDoc() {
 const xhttp = new XMLHttpRequest();
 const url = "https://jsonplaceholder.typicode.com/albums";
 xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML =
     this.responseText;
   }
 };

 xhttp.open("GET", url, true);
 xhttp.send();
}
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>

<div id="demo"></div>

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2016-03-19
    • 2012-06-05
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多