Cold Tea

那些我们一直惴惴不安 而又充满好奇的未来 在我心里 隐隐约约地感觉到它们是明亮的

您当前所在的位置是:首页>博文列表>

使用原生JS封装ajax方法

当项目只需要使用ajax而不需要引用jquery时,此时封装一个ajax方法非常必要,下面给出主要代码


	function ajax(obj){
		obj.method = obj.method.toUpperCase()||'POST';
		obj.url = obj.url||'';
		obj.async= obj.async||true;
		obj.data = obj.data||null;
		obj.success = obj.success ||function(){};
		//新建xml对象
		var xml= null;
		if(window.XMLHttpRequest){

			xml= new XMLHttpRequest();
		}else{
		//兼容IE
			xml= new ActiveXObject("Microsoft.XMLHTTP");
		}

		var arr = [];
		for(attr in obj.data){
			arr.push(attr+'='+obj.data[attr]);
		}
		var postData = arr.join('&');

		if(obj.method.toUpperCase()==='POST'){
		//当请求方式为‘POST’时	
			xml.open(obj.method,obj.url,obj.async);
			xml.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
			xml.send(postData);
		}else if(obj.method.toUpperCase()=='GET'){
			//当请求方式为‘GET’时	
			xml.open(obj.method,obj.url,obj.async);
			xml.send(null);
		}
		//设置回调函数
		xml.onreadystatechange=function(){
			if(xml.readyState==4&&xml.status==200){
				obj.success(xml.responseText);
			}
		}

	}

				

函数使用实例:

					ajax({
						method:'POST',
						url:'test.php',
						data:{
							name1:'value1',
							name2:'value2'
						}
						success:function(response){
							dosomethingwith(response);
						}
					})