<!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"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" src="scripts/jquery.js"></script> </head> <style> * { margin: 0px; padding: 0px; } #box { float: left; width: 500px; } #left { float: left; background: #090; width: 100px; height: 100px; } #right { background: #c60; width: 100px; height: 100px; float: left; } #box2 { width: 180px; height: 100px; } html>body #box2 { width: auto; height: auto; min-width: 180px; min-height: 100px; } </style> <body> <p id="box"> <p id="left">点击我 看效果!</p> <p id="right">fffeeee</p> </p> <p style="width:100px; height:100px; background:#969; float:left;" id="dd">dddd</p> <script> // 异步请求封装 ie6即以上浏览器 // ajax(url,fnsucc,selectid,fnfaild) //url 请求地址 //fnsucc 异步请求后的内容处理函数 //fnfaild 请求失败处理函数 function ajax(url,fnsucc,fnfaild) { //1.创建ajax对象 //非ie6 var oajax; if(window.xmlhttprequest)//不会报错,只会是undefined {oajax=new xmlhttprequest();} else //ie6 ie5 {oajax=new activexobject("microsoft.xmlhttp");} //alert(oajax); //2.连接服务器 //open(方法,文件名,异步传输) oajax.open("get",url,true);//制止缓存 //3.发送请求 oajax.send(); //4.接收返回值 和服务器通讯的时候此事件发生 oajax.onreadystatechange=function() { //oajax.readystate //浏览器和服务器,进行到哪一步了 异步握手过程 if(oajax.readystate==4)//读取完成(可能文件不存在) { if(oajax.status==200 || oajax.status==304)//请求成功 304即使浏览器缓存了也返回数据 { fnsucc(oajax.responsetext); //alert("成功"+oajax.responsetext); } else { if(fnfaild)//fnfaild传进来时 { fnfaild(oajax.status); } //alert("失败:"+oajax.status);//status为404 } } } } window.onload=function(){ var obtn=document.getelementbyid("left"); obtn.onclick=function() { ajax("http://28967904.jsp.jspee.cn/ext/singlepage/list/json-1-1-20",function(str){ var da= json.parse(str); //json数据解析 alert(da.totalrow) },function(erorr){ console.log('请求出错:'+erorr); }) } } </script> </body> </html>
以上就是原生javascript实现的ajax异步封装功能示例的内容。
