封装ajax

模仿jQuery中ajax的功能。自己封装了一个简单的ajax实现函数。用来练手的,里面没有考虑安全性问题。

ajax.js

/**
* Date 2012-11-3
* 
*/
function ajax(options){
	/**
	*创建xmlHttpRequest对象
	*对于不同的浏览创建xmlHttpRequest的对象所使用的方法不同
	*
	*/
	var xmlHttp=null;
	if(typeof(xmlHttp)=="undefined" || xmlHttp==null){
		try{
			xmlHttp = new XMLHttpRequest();
		}catch(e1){
			try{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e2){
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
		}
	}
	
	/**  create END **/
	
	/**
	*属性参数,先写几个作为测试,以后会陆续增加
	*/
	var default_options={
		url:"",
		method:"GET",
		async:true,
		data:"",
		success:"",
	};
	/** 属性 END **/
	
	//判断请求中是否带有url参数,没有的话则不给处理
	if(typeof(options.url)=='undefined' || options.url==""){
		alert("调用ajax请求时,url不能为空!!");
		return;
	}
	//如果请求方式也没写的话,则使用默认的设置
	if(typeof(options.method)=='undefined' || options.method==""){
		options.method=default_options.method;
	}
	//请求模式为空使用默认设置,默认使用异步请求
	if(typeof(options.async)=='undefined' || options.async==""){
		options.async=default_options.async;
	}
	/**
	*请求参数,get方式与post方式请求发送参数的方式不同。如果是get方式直接
	*将参数连接到url后面
	*/
	if(options.method.toLowerCase()=="get"){
		if(typeof(options.data)!='undefined' && options.data!="" && options.data!=null){
			options.url+="?"+options.data;
		}
	}
	//连接服务器
	xmlHttp.open(options.method,options.url,options.async);
	
	//发送请求的数据 GET方式与post方式请求时传送参数的方式不同。分开对待
	if(options.method.toLowerCase()=="post"){
		xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlHttp.send(options.data);
	}else{
		xmlHttp.send(null);
	}
	//异步请求状态发生改变时,执行的函数
	eval(options.success);
	xmlHttp.onreadystatechange=function(){
		//readyState==4请求已完成  status==200服务器响应完成
		if(xmlHttp.readyState==4 && xmlHttp.status==200){
			//执行响应的结果
			eval(options.success(xmlHttp.responseText));
			xmlHttp=null;
		}
	}
}

测试代码Test.html

<html>
	<head>
	<script type="text/javascript" src="js/ajax.js"></script>
	<script type="text/javascript">
		function load(){
			/*createXmlHttpRequest();
			open("GET","ajax.php",false,"showResult()");
			*/
			ajax({
				url:"ajax.php",
				method:"POST",
				data:"username=M1&password=P1",
				success:function(msg){
					alert(msg);
				}
			});
			
		}
		
	</script>
	</head>
	<body οnlοad="load();">
	</body>
</html>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值