【问题标题】:Displaying JSON data to browser向浏览器显示 JSON 数据
【发布时间】:2021-03-04 05:46:24
【问题描述】:

我有以下 JSON 数据:

{"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.368999999999999772626324556767940521240234375,"src":"us","eqid":"c0001xgp","magnitude":8.800000000000000710542735760100185871124267578125,"lat":38.3220000000000027284841053187847137451171875},{"datetime":"2012-04-11 06:38:37","depth":22.89999999999999857891452847979962825775146484375,"lng":93.06319999999999481588019989430904388427734375,"src":"us","eqid":"c000905e","magnitude":8.5999999999999996447286321199499070644378662109375,"lat":2.31099999999999994315658113919198513031005859375},{"datetime":"2007-09-12 09:10:26","depth":30,"lng":101.3815000000000026147972675971686840057373046875,"src":"us","eqid":"2007hear","magnitude":8.4000000000000003552713678800500929355621337890625,"lat":-4.51719999999999988204990586382336914539337158203125}]}

我正在尝试向浏览器显示上述一些数据,但我却在浏览器中显示了这些数据。

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

我的代码是

var xmlhttp = new XMLHttpRequest();

      xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
          if (xmlhttp.status == 200) {
            const jsonResponse = JSON.parse(xmlhttp.responseText);
            for (response in jsonResponse)
            // console.log(jsonResponse[response])
            $('#result1').html(`${jsonResponse[response]}`);
          } else {
            alert('Problem in parsing JSON data via AJAX');
          }
        }
      };

当我使用 console.log(jsonResponse[response]) 时,我可以看到数据数组,但不知道如何让它正确显示在浏览器上。

提前感谢您的帮助。

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow!你检查过this question的答案吗?当您用反引号括起来 JSON 数据时,它会被字符串化为 [object Object]。如果您仍想使用反引号,请考虑以下更改:JSON.stringify(jsonResponse[response])
  • 感谢您的热烈欢迎,我会查看链接。

标签: javascript json ajax xmlhttprequest


【解决方案1】:

问题是您在字符串文字中传递一个对象而没有将对象字符串化 $('#result1').html(`${jsonResponse[response]}`); 实际上应该是 $('#result1').html(`${JSON.stringify(jsonResponse[response])}`);

【讨论】:

    【解决方案2】:

    您不能使用 html 显示对象。相反,您可以将 json 转换为字符串并使用 JSON.stringify 显示并将其包装在 pre 标记中。

    $('#result1').html(`<pre>${jsonResponse[response]}</pre>`)
    

    【讨论】:

    • 感谢马图的回复。
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多