一、知识要点
1、GET请求
2、eval的使用(读取JSON)
3、创建元素document.createElement('li')
4、innerHTML的使用
二、源码参考
<!DOCTYPE >
<html>
<head>
<title></title>
<meta charset="utf-8">
<style>
</style>
<script src="ajax.js" type="text/javascript" charset="utf-8"></script>
<script>
window.onload = function() {
var btn1 = document.getElementById('btn1');
var ul1 = document.getElementById('ul1');
btn1.onclick = function() {
ajax('data.json', function(success) {
var result = eval(success); // eval转为JSON对象
// <li>用户名:张三,密码:123456</li>
for(var i = 0; i < result.length; i++) {
var oLi = document.createElement('li')
oLi.innerHTML = '用户名:' + result[i].user + ",密码:" + result[i].pass;
ul1.appendChild(oLi);
}
}, function(err) {
alert(err)
})
}
}
</script>
</head>
<body>
<input type="button" name="btn1" id="btn1" value="读取" />
<ul id="ul1">
</ul>
</body>
</html>
ajax封装
function ajax(url, fnSucc, fnFaild) {
//1.创建Ajax对象
if (window.XMLHttpRequest) {
var oAjax = new XMLHttpRequest();
} else {
var oAjax = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.连接服务器(打开和服务器的连接)
oAjax.open('GET', url, true);
//3.发送
oAjax.send();
//4.接收
oAjax.onreadystatechange = function () {
if (oAjax.readyState == 4) {
if (oAjax.status == 200) {
//alert('成功了:'+oAjax.responseText);
fnSucc(oAjax.responseText);
} else {
//alert('失败了');
if (fnFaild) {
fnFaild();
}
}
}
};
}
JSON数据
[{
user: 'blue',
pass: '123456'
}, {
user: '张三',
pass: '654321'
}, {
user: '李四',
pass: '789456'
}, {
user: '王五',
pass: '7777'
}]
网友评论