XMLHttpRequest获取JSON文件的内容,但返回[object object]

时间:2018-12-12 23:19:42

标签: javascript json

我正在遵循w3schools的指南,试图更好地理解JSON。

这是他们的代码 https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

这是他们的示例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>

我在这里还有另一个要使用的示例JSON文件 https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json

使用相同的代码,除了更改

  

document.getElementById(“ demo”)。innerHTML = myObj.name;

  

document.getElementById(“ demo”)。innerHTML = myObj;

似乎没有带回[对象对象]以外的任何东西,我不明白为什么,有人可以帮忙吗,谢谢

  <!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>

1 个答案:

答案 0 :(得分:1)

如果要将接收到的JSON对象打印到DOM,则需要将其转换为字符串。为此,请使用erl -pa /path/to/myapp/ebin -name myapp@myremote.host -setcookie mycookie -shell -eval "application:start(myapp)."