Ajax简单应用
new_ajax.js文件
function ajax(url,funsuc,funFailed){
//非IE6的浏览器用new XMLHttpRequest()
//IE6用new ActiveXObject("Microsoft.XMLHTTP")
//1.创建Ajax对象
if(window.XMLHttpRequest){
var oAjax=new XMLHttpRequest();
}else{
var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
}
//2.连接数据库 open(方法,文件名,异步传输)
oAjax.open('GET',url,true);//'aaa.txt?ne='+new Date().getTime() 去掉缓存
//3.发送请求
oAjax.send();
//4.接收返回 当与数据库有通讯时触发
oAjax.onreadystatechange=function(){
if(oAjax.readyState==4){
//0 未初始化 还没有调用open()方法
//1 载入 已调用send()方法,正在发送请求
//2 载入完成 send()方法完成,已收到全部响应内容(可能是加密过的或压缩的数据不能直接用)
//3 解析 正在解析响应内容
//4 完成 响应内容解析完成,可以在客户端调用了
if (oAjax.status==200){
funsuc(oAjax.responseText);
}else{
if(funFailed){
funFailed(oAjax.status)
}
}
}
}
}
html文件调用js文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script src="new_ajax.js"></script>
<script type="text/javascript">
window.onload=function(){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
ajax('aaa.txt',function(str){
alert(str);
});
}
}
</script>
</head>
<body>
<input id="btn1" type="button" name="" value="读取">
</body>
</html>