1.创建Ajax对象
2.连接服务器
3.发送请求
4.接收返回值
eg: 取‘123.txt’中的数据:
1.创建Ajax对象(两种方法创建)
- ie6:newActiveXObject("Microsoft.XMLHTTP");
- 其他:newXMLHttpRequest();
兼容写法:
var oAjax=null; if(window.XMLHttpRequest){ //必须判断属性,不能用变量 oAjax=new XMLHttpRequest(); } else{ oAjax=new ActiveXObject("Microsoft.XMLHTTP"); }
2.连接服务器
open(方法,url,是否异步),我们要取123.txt中的数据。
oAjax.open('GET','123.txt',true);
3.发送请求
send()
oAjax.send();
4.接收返回值,请求状态监控
onreadystatechange事件:
- readystate属性:请求状态
0:未初始化
1:已调用send()方法,真正该发送请求
2:send()方法已完成,已收到全部相应内容(可能被加密了)
3:正在解析相应内容(解析成js能理解的东西)
4:相应内容解析完成,不代表是否成功
- status表示是否成功。200成功,30*重定向,404没找到。
-responseText 取回服务器返回的数据
oAjax.onreadystatechange=function(){ if(oAjax.readyState==4){ if(oAjax.status==200){ alert('成功'+oAjax.responseText); }<pre name="code" class="javascript"> <span style="font-family: Arial,Helvetica,sans-serif;">else{</span>alert('失败');}}};
将ajaxj抽象成函数,供以后调用:
function ajax(url,fnSucc,fnFaild){ var oAjax=null; if(window.XMLHttpRequest){ oAjax=new XMLHttpRequest(); } else{ oAjax=new ActiveXObject("Microsoft.XMLHTTP"); } oAjax.open('GET',url,true); oAjax.send(); oAjax.onreadystatechange=function(){ if(oAjax.readyState==4){ if(oAjax.status==200){ fnSucc(oAjax.responseText); } else{ if(fnFaild){ fnFaild(); } } } }; }测试:
oBtn.onclick=function(){ ajax('123.txt',function(str){ alert(str); },function(){ alert('失败'); }) };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。