封装Ajax

2016-11-18 08:09:04来源:CSDN作者:sinat_36146776人点击

<!doctype html><html lang="en"><head>	<meta charset="UTF-8">	<title>EMS</title>	<style type="text/css">		#ems{			position: absolute;			left: 50%;			width: 400px;			height: auto;			margin-left: -200px;			background: lightGreen;			text-align: center;			min-height: 50px;			height: 500px;			overflow-y: scroll;			overflow-x: hidden;		}		#ems input{			height: 25px;			margin-top: 10px;		}		#list{			background: lightBlue;		}		#list li{			text-align: left;		}	</style>	</head><body><div id="ems">	<div>		<input type="text" id="code">		<input type="button" value="查询" id="btn">	</div>	<div id="list">	</div></div><script type="text/javascript">function ajax(data){	// data={data:"",dataType:"xml/json",type:"get/post",url:"",asyn:"true/false",success:function(){},failure:function(){}};	// data:{username:123,password:456}//对象  get时给url	// data='?username=123&password=456';//get	var xhr=null;	if(window.XMLHttpRequest){		xhr=new XMLHttpRequest();	}else{		xhr=new ActiveXObject('Microsoft.XMLHTTP');	}	var type=data.type=='get'?'get':'post';	var url='';	if(data.url){		url=data.url;		if(data.type=='get'){			// url+='?'+data.data;//不能解决缓存问题			url+='?'+data.data+'&_t='+new Date().getTime();//加上当前毫秒时间,改变了url		}	}	var flag=data.asyn=='true'?'true':'false';	xhr.open('get',url,true);//get会缓存	if(type=='get'){		xhr.send(null);	}else if(type=='post'){		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//对传入的参数进行编码		xhr.send(data.data);	}	xhr.onreadystatechange=function(){		if(this.readyState==4){			if(this.status==200){				if(typeof data.success=='function'){					var d=data.dataType=='xml'?xhr.responseXML:xhr.responseText;					data.success(d);				}			}else{				if(typeof data.failure=='function'){					data.failure();				}			}		}	}}//调用window.onload=function(){	var btn=document.getElementById('btn');	btn.onclick=function(){		var param={			url:'00data.php',			type:'get',			dataType:'json',			success:function(data){				alert(data);			}		};		ajax(param);	}}</script></body></html>

00data.php

<?php echo 1; ?>
结果如下








最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台