原生ajax的get和post方法封装

get和post是ajax中常用的请求方式
get一般用于获取数据;
post一般用于发送数据;
get请求特点
1.get请求如果需要传递参数,那么会默认将参数拼接到url的后面;然后发送给服务器;
2.get请求传递参数大小是有限制的;是浏览器的地址栏有大小限制;IE不超过2K;谷歌不超过8K;超过会自动截掉;
3.get安全性较低
4.get 一般会走缓存,为了防止走缓存,给url后面每次拼的参数不同;
放在?后面,一般用个时间戳;
post的请求特点
1.post传递参数,需要把参数放进请求体中,发送给服务器;
2.post请求参数放进了请求体中,对大小没有要求;
3.安全性比较高;
4.post请求不会走缓存;
get请求方式的封装

function ajaxGet(url,cb){
			var xhr = new XMLHttpRequest();
			xhr.open("GET",url);
			xhr.send();
			xhr.onreadystatechange = function(){
			if(xhr.readyState === 4 && xhr.status === 200){
				// 只有在此处才能拿到数据,因为此处是事件处理函数,又不能使用return返回数据
				// 所以要利用回调函数(将执行结果以参数的形式传给回调函数,然后在回调函数中打印)
					cb(xhr.responseText);
				}	
			}
		}

使用方式示例:

document.onclick = function(){
			var dizhi = "http://localhost/ajax/data/data.php?abc=123&qwe=456&asd=hello";
			ajaxGet(dizhi,function(res){
				console.log(res);
			});
		}

post请求方式的封装

function ajaxPost(url,cb,data){
			var xhr = new XMLHttpRequest();
			xhr.open("POST",url);
			
			// 设置发送头信息,中,发送数据的格式,为表单数据格式
			xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			xhr.send(data);
			xhr.onreadystatechange = function(){
				if(xhr.readyState === 4 && xhr.status === 200){
					cb(xhr.responseText);
				}
			}
		}

使用方式示例:

document.onclick = function(){
			var dizhi = "http://localhost/ajax/data/data.php";
			ajaxPost(dizhi,function(res){
				console.log(res);
			},"abc=987&zxc=hello");
		}

get和post请求方式的组合封装

function ajax(ops){
			// 先处理默认属性
			ops.type = ops.type || "get";
			ops.data = ops.data || "";
			// 根据当前的请求方式,决定是否需要拼接数据,处理url
			ops.url = ops.type == "get" ? ops.url + "?" +ops.data : ops.url;
			// 创建xhr对象
			var xhr = new XMLHttpRequest();
			// 开启请求
			xhr.open(ops.type,ops.url);
			// 根据类型决定send的内容及内容数据格式
			if(ops.type == "get"){
				xhr.send();
			}else{
				xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			}
			// 开启监听
			xhr.onreadystatechange = function(){
				if(xhr.readyState === 4 && xhr.status ===200){
					// 执行回调函数,取出数据
					ops.success(xhr.responseText);
				}
			}
		}

使用方式示例:

document.onclick = function(){
					var url = "http://localhost/ajax/data/get-post.php" ;
					ajax({
						success:function(res){
							console.log(res);
						},
						url:url,
						type:"get",
						data:"user=admin&pass=123"
					});
				}

注意:
这里的地址使用的是绝对路径,地址的位置如下布局
在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值