AJAX请求JSON文件

AJAX 可用来与 JSON文件进行交互式通信。
在这里插入图片描述
按钮btn添加点击事件
JavaScript 调用的服务器页面是名为 “DOM4.json” 的JSON 文件。
页面代码

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
	<script type="text/javascript">
		window.onload = function() {
			var btn = document.querySelector('button');
			btn.addEventListener('click',function() {
				//创建JSON对象
				var xmlHttp = new XMLHttpRequest();
				//准备发送请求
				xmlHttp.open('GET','DOM4.json',true);
				//发送请求
				xmlHttp.send();
				//事件监听
				xmlHttp.onreadystatechange = function() {
					if(xmlHttp.readyState==4 && xmlHttp.status==200){
						 var jsonObj = JSON.parse(this.responseText);
						console.log(jsonObj.basic.location);
					}
				}
				
			});
		}
	</script>
</head>
<body>
	<button type="button">点击</button>
</body>
</html>

对应JSON文件代码:

{
	"basic":{"cid":"CN101050311","location":"西安","parent_city":"牡丹江","admin_area":"黑龙江","cnty":"中国","lat":"44.5810318","lon":"129.6131134","tz":"+8.00"},
	"update":{"loc":"2020-06-20 15:12","utc":"2020-06-20 07:12"},
	"status":"ok",
	"now":{"cloud":"100","cond_code":"399","cond_txt":"雨","fl":"19","hum":"86","pcpn":"0.6","pres":"971","tmp":"19","vis":"16","wind_deg":"190","wind_dir":"南风","wind_sc":"2","wind_spd":"10"}
}
	
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值