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"}
}