原生javascript实现的ajax异步封装功能示例
本文实例讲述了原生javascript实现的ajax异步封装功能。分享给大家供大家参考,具体如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>无标题文档</title>
<scripttype="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>
<divid="box">
<divid="left">点击我看效果!</div>
<divid="right">fffeeee</div>
</div>
<divstyle="width:100px;height:100px;background:#969;float:left;"id="dd">dddd</div>
<script>
//异步请求封装IE6即以上浏览器
//ajax(url,fnSucc,selectID,fnFaild)
//url请求地址
//fnSucc异步请求后的内容处理函数
//fnFaild请求失败处理函数
functionajax(url,fnSucc,fnFaild)
{
//1.创建Ajax对象
//非IE6
varoAjax;
if(window.XMLHttpRequest)//不会报错,只会是undefined
{oAjax=newXMLHttpRequest();}
else
//iE6IE5
{oAjax=newActiveXObject("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(){
varoBtn=document.getElementById("left");
oBtn.onclick=function()
{
ajax("http://28967904.jsp.jspee.cn/ext/singlePage/list/json-1-1-20",function(str){
varda=JSON.parse(str);//JSON数据解析
alert(da.totalRow)
},function(erorr){
console.log('请求出错:'+erorr);
})
}
}
</script>
</body>
</html>
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript中ajax操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。