需求:点击按钮在局部区域显示后台返回的数据
前台代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>初识异步效果和json数据格式</title>
<script>
//需求:点击按钮在div中显示数据
window.onload = function(){
var btn = document.getElementById('btn');
btn.onclick = function(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
xhr.open('get','02.php');
xhr.send(null);
console.log(1);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var date = xhr.responseText;
var d = JSON.parse(date);
var tag = '<div><span>'+ d.name +'</span><span>-------</span><span>'+ d.age +'</span></div>';
var box = document.getElementById('box');
box.innerHTML = tag;
console.log(2);
}
}
}
console.log(3);
}
}
</script>
</head>
<body>
<div id="box">
</div>
<input type="button" value="显示数据" id="btn">
</body>
</html>
后台代码:
<?php
$arr = array("name"=>"张三","age"=>"18");
echo json_encode($arr);//转换成json形式的字符串
?>
运行结果: