JSON基础入门实战讲解在线视频课程-JSON.parse()从服务端接收 JSON 数据

版权声明:黄菊华 https://blog.csdn.net/u013818205/article/details/86626025

从服务端接收 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基础入门实战讲解在线视频课程
https://edu.csdn.net/course/detail/10088JSON基础入门实战讲解在线视频课程-JSON.parse()从服务端接收 JSON 数据

猜你喜欢

转载自blog.csdn.net/u013818205/article/details/86626025
今日推荐