87,904
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button onclick="visitJSON()">用ajax异步访问json</button>
</body>
</html>
<script src="../../Scripts/jquery-1.9.1.js"></script>
<script>
function createXhr() {
try {
AjaxRequest = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
AjaxRequest = false;
}
}
}
if (!AjaxRequest) {
alert("Error initializing XMLHttpRequest!");
return false;
} else {
return AjaxRequest;
}
}
function visitJSON() {
var xhr = createXhr();
xhr.open("get", "users.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = xhr.responseText;
console.log(xhr.responseText);
var obj = JSON.parse(res);
console.log(obj);
for (var i = 0; i < obj.length; i++) {
console.log("用户名称:" + obj[i].uname);
console.log("用户密码:" + obj[i].age);
console.log("用户性别:" + obj[i].gender);
}
}
}
xhr.send(null);
}
</script>