使用Ajax异步加载请求JSON数据
程序员文章站
2024-01-25 20:07:22
...
html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="addLoadEvent.js"></script>
<script src="getHttpObject.js"></script>
<script src="getNewContent.js"></script>
</head>
<body>
</body>
</html>
demo.json
[
{
"name":"Lee",
"age":28,
"height":188
},
{
"name":"Sun",
"age":30,
"height":190
}
]
addLoadEvent.js
function addLoadEvent(fun){
var oldLoad = window.onload;
if(typeof oldLoad != "function"){
window.onload = fun;
}else{
window.onload = function(){
oldLoad();
fun();
}
}
}
getHttpObject.js
/*建立XMLHttpRequest对象的兼容方法*/
function getHttpObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
getNewContent.js
function getNewContent(){
/*建立一个新的getHttpObject对象*/
var XHR = getHttpObject();
if(XHR){
XHR.onreadystatechange = function(){
if(XHR.readyState == 4 && XHR.status == 200){
var txt = JSON.parse(XHR.responseText);
var result = [];
/*动态添加DOM*/
var body = document.getElementsByTagName("body")[0];
var content = document.createElement("p");
body.appendChild(content);
/*遍历输出*/
for(var i=0;i<txt.length;i++){
result["name"] = txt[i].name;
result["age"] = txt[i].age;
result["height"] = txt[i].height;
content.innerHTML += "姓名:"+result["name"]+" 年龄:" + result["age"] +" 身高:"+ result["height"]+"<br/>";
}
}
};
/*异步请求触发后,脚本会继续执行,不会等待它响应*/
XHR.open('Get','demo.json?id='+Math.random(),true);
XHR.send(null);
}
}
addLoadEvent(getNewContent);