[英]Difficulty accessing JSON file's content
I would like to access this JSON file and refer to its properties.我想访问这个 JSON 文件并参考它的属性。 I've tried JSON,parse() but this doesn't seem to work as '[object Object]' is what is returned.
我试过 JSON,parse() 但这似乎不起作用,因为 '[object Object]' 是返回的内容。
var para = document.getElementById("para");
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json");
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseText);
para.innerHTML = obj;
}
};
If you console.log()
the obj, it will work.如果你
console.log()
obj,它会工作。
Before you pass it into element.innerHTML
you have to stringify it again with JSON.stringify(JSON)
to convert it from an Object to a JSON string.在将它传递到
element.innerHTML
之前,您必须再次使用JSON.stringify(JSON)
对其进行字符串化,以将其从 Object 转换为 JSON 字符串。 So you might as well pass the responseText
into the innerHTML
所以你不妨将
responseText
传入innerHTML
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
para.innerHTML = xhr.responseText;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.