ajax封装

本文主要介绍如何对Ajax进行封装,通过示例展示HTML和JS代码,帮助理解Ajax的封装过程。
摘要由CSDN通过智能技术生成

封装ajax

html代码 :

<button id='get1'>get</button>
<button id='post1'>post</button>

js代码 :

<script>
	function $ajax({method="get",url,data,success,error,asnyc=true}){
		xhr = null //存放ajax对象用的变量

		try{
			xhr = new XMLHttpRequest()  //IE8
		}catch(error){
			xhr = new ActiveXObject("Microsoft.XMLHTTP");  //IE8以下
		}

		//判断需不需要传参
		if(data){
			//{'name':'张三',age:18}  让用户传这个对象格式的参数
			//通过自定义的haha函数,把对象格式转换成"张三"&age=18'这个格式
			//'name="张三"&age=18'
			 data = haha(data)
		}

		if(method.toLocaleLowerCase() == 'get' && data){
			//看你是不是用的get方法,同时传参了
			url+= "?"+data    // 1.php?name="张三"&age=18
		}

		//初始化
		xhr.open(method,url,asnyc)

		//判断你使用get还是post方法
		if(method.toLocaleLowerCase() == 'get'){
			xhr.send()
		}else{
			//post传参需要设置请求头
			xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

			//判断你有参数吗
			if(data){
				xhr.send(data)  // xhr.send('name="张三"&age=18')
			}else{
				xhr.send()
			}
		}
           
		//状态码开始发生变化了0-4
		xhr.onreadystatechange=function(){
			if(xhr.readyState == 4){
				if(xhr.status == 200){
					//回调函数,先判断用户传参没,要是没传参数就是不想处理响应数据
					if(success){
						success(xhr.response)
					}
				}else{
					if(error){
						//请求失败,把错误码当做参数给回调函数error装进去
						error(xhr.status)
					}
				}
			}
		}

		//处理参数的函数
		function haha(a){
			var str = '';
			for(bb in a ){
				//遍历对象
				str += bb +"="+a[bb]+"&"
			}
			return str.substring(0,str.length-1);
            //截取字符串不拿最后一个&
		}
	}
	
	var get1 = document.getElementById('get1')
	var post1 = document.getElementById('post1')

	get1.onclick=function(){
		$ajax({
			data:{'name':'张三','age':18,sex:'男'},
			url:'1.php',
			method:'get',
			success:function(da){
				console.log(da)
				console.log('哈哈哈就是这么666')
			}
		})
	}

	post1.onclick=function(){
		$ajax({
			data:{'name':'张三','age':18,sex:'男'},
			url:'2.php',
			method:'post',
			success:function(da){
				alert(3)
				console.log('我是成功后执行的函数')
				console.log(da)
				console.log('我是成功后执行的函数')
			},
			error:function(da){
				console.log('您当前的错误码是'+da)
			}
		})
	}
</script>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值