javascript中Ajax的简单应用

来源:互联网 发布:安装阿里云的yum源 编辑:程序博客网 时间:2024/06/07 11:07

一、ajax是浏览器与服务器之间的一个异步通信机制,用来无刷新的读取数据

二、在这个demo中,我用到的服务器是wamp,大家可以自己下一个64位/32位,具体配置过程百度。

三、最后跑之前要把html和js文件放进wamp安装目录下的www文件夹中,并运行wamp,然后打开你写的index.html

四、在浏览器中F12中的Network下查看ajax的读取。如果上一步的wamp没打开,就会报错

五、此demo比较简陋,多次点击会多次读取,因为没有写缓存的部分,请自行补充判断是否加载。或者参考另一篇文章jQ的ajax

以下是代码,具体步骤见注释

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ajax的使用</title>
<script src="js/oAjax.js">

</script>
<script type="text/javascript">
window.onload=function()
{
var oBtn=document.getElementById('btn1');
oBtn.onclick=function()
{
ajax('a.txt?t='+new Date().getTime(),function(str){
alert(str);
});
}
}
</script>
</head>
<body>
<input type="button" name="" id="btn1" value="读取文件" />
</body>
</html>

-------------------js-----------------------


function ajax(url,funSuccess,funFail){//三个参数url,成功时的回调函数,失败回调函数
//step1:创建一个ajax对象
if(window.XMLHttpRequest)//非ie6
{
var oAjax=new XMLHttpRequest();
}else{
var oAjax=new ActiveXObject("Microsoft.XMLHTTP");//ie6
}

//step2:打开连接(连接到服务器)
oAjax.open('GET',url,true);

//step3:发送请求
oAjax.send();

//step4:接收返回值
oAjax.onreadystatechange=function(){
if(oAjax.readyState==4){
if(oAjax.status==200){//成功
//成功时执行操作,以函数作为参数
//responseText请求读取的文件
funSuccess(oAjax.responseText);
}else{
//失败时执行操作
//alert(oAjax.status);
if(funFail){
{
funFail(oAjax.status);
}
}
}
}
}
};

原创粉丝点击