read_and_create.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="ajax.js"></script>
<script>
window.onload=function ()
{
var oBtn=document.getElementById('btn1');
var oUl=document.getElementById('ul1');
oBtn.onclick=function ()
{
ajax('data.txt?t='+new Date().getTime(), function (str){
var arr=eval(str);
for(var i=0;i<arr.length;i++)
{
var oLi=document.createElement('li');
oLi.innerHTML='用户名:<strong>'+arr[i].user+'</strong>密码:<span>'+arr[i].pass+'</span>';
oUl.appendChild(oLi);
}
}, function (){
alert('失败');
});
};
};
</script>
</head>
<body>
<input id="btn1" type="button" 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.连接服务器
//open(方法, 文件名, 异步传输)
oAjax.open('GET', url, true);
//3.发送请求
oAjax.send();
//4.接收返回
oAjax.onreadystatechange=function ()
{
//oAjax.readyState //浏览器和服务器,进行到哪一步了
if(oAjax.readyState==4) //读取完成
{
if(oAjax.status==200) //成功
{
fnSucc(oAjax.responseText);
}
else
{
if(fnFaild)
{
fnFaild(oAjax.status);
}
//alert('失败:'+oAjax.status);
}
}
};
}