[英]XMLHttpRequest to get the content of a JSON file but it returns [object object]
I am following a guide from w3schools trying to understand JSON better. 我正在遵循w3schools的指南,试图更好地理解JSON。
This is their code https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax 这是他们的代码https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
This is their sample JSON file https://www.w3schools.com/js/json_demo.txt 这是他们的示例JSON文件https://www.w3schools.com/js/json_demo.txt
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>
</body>
</html>
I have another example JSON file here that I want to use https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json 我在这里还有另一个示例JSON文件,我想使用https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json
Using the same code, apart from changing 使用相同的代码,除了更改
document.getElementById("demo").innerHTML = myObj.name;
document.getElementById(“ demo”)。innerHTML = myObj.name;
to 至
document.getElementById("demo").innerHTML = myObj;
document.getElementById(“ demo”)。innerHTML = myObj;
It doesn't seem to bring back anything apart from [object object] and I cannot understand why, Could someone please help, thanks 它似乎没有带回[对象对象]以外的任何东西,我不明白为什么,有人可以帮忙吗,谢谢
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj;
}
};
xmlhttp.open("GET", "https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json", true);
xmlhttp.send();
</script>
</body>
</html>
If you want to print the received JSON object to the DOM, you'll need to turn it into a string. 如果要将接收到的JSON对象打印到DOM,则需要将其转换为字符串。 To do this, use
JSON.stringify(responseText)
. 为此,请使用
JSON.stringify(responseText)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.