<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax学习_http_request</title>
<script>
//1.HttpRequest初始化,判断浏览器类型
var request = null;
var checkUserName = function(){
if(window.XMLHttpRequest()){ //火狐,苹果
request = new XMLHttpRequest();
}else if(window.ActiveXObject()){ //IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.通过对象打开请求
if(request){
request.open("GET","user.json",true); //true代表服务器返回时间内是否执行以下的代码
request.send(null); //3.发送请求
request.onreadystatechange = callBack;
}
}
function callBack(){
if(request.readyState == 4){
if(request.status == 0){
var response = request.responseText;
var user = eval("("+response+")").group;
for(var i=0; i<=user.length; i++){
console.log("name="+user[i].name+" age="+user[i].age);
}
}
}
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" id="username" οnblur="checkUserName()"></td>
</tr>
</table>
<span id="showMessage"></span>
</body>
</html>
json文件内容:
{
"group" : [
{"name": "justin" , "age": "20"},
{"name": "Jan" , "age": "22"},
{"name": "Boss" , "age": "30"}
]
}