Ajax学习
ajax 请求:
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事件: -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('失败'); }) }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |