Javascript 向浏览器显示JSON数据
我有以下JSON数据:Javascript 向浏览器显示JSON数据,javascript,json,ajax,xmlhttprequest,Javascript,Json,Ajax,Xmlhttprequest,我有以下JSON数据: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.368999999999999772626324556767940521240234375,"src":"u
{"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])时,我可以看到数据数组,但无法确定如何使其正确显示在浏览器上
提前感谢您的帮助。问题是您正在以字符串文本形式传递对象,而没有对对象进行字符串化
$('#result1').html(`jsonResponse[response]}`)
实际上应该是$('#result1').html(`${JSON.stringify(jsonResponse[response])}`)代码>不能使用html显示对象。相反,您可以将json转换为字符串并使用json.stringify
显示,然后将其包装在pre
标记中
$('#result1').html(`<pre>${jsonResponse[response]}</pre>`)
$('#result1').html(`${jsonResponse[response]}`)
嘿,欢迎来到Stack Overflow!你查过你的答案了吗?当您使用背景标记将JSON数据字符串化为[object]。如果您仍然想使用回扣,请考虑此更改:<代码> JSON.StrugIDENT(JSONREST(响应))<代码>谢谢您的热情欢迎,我将查看链接。感谢您的回复Mathu。谢谢您的回复。