当前阅读教程:JSON教程 > 从服务端接收 JSON 数据 | |
阅读(22555525) 收藏 赞(5685) 分享 | |
上一篇: JSON.parse() | 下一篇: 从服务端接收数组的 JSON 数据 |
我们可以使用 AJAX 从服务器请求 JSON 数据,并解析为 JavaScript 对象。 实例代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS中文教程网 8939.org</title> </head> <body>
<h2>使用 XMLHttpRequest 来获取文件内容</h2> <p>文件内容是标准的 JSON 格式,可以使用 JSON.parse 方法将其转换为 JavaScript 对象。</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "http://www.8939.org/json/json_demo.txt", true); xmlhttp.send();
</script>
<p>查看 JSON 文件数据 <a href="http://www.8939.org/json/json_demo.txt" target="_blank">json_demo.txt</a></p>
</body> </html> json_demo.txt 代码如下 {"name":"myweb","num":3} |
|
上一篇: JSON.parse() | 下一篇: 从服务端接收数组的 JSON 数据 |