get、post、jsonp的封装

get、post、jsonp的封装

get与post的区别

get与post都可以在ajax中都可以用来发送数据,那么它们两者的区别如下:

  1. POST主要用来发送数据,GET主要用来接受数据;
  2. PSOT发送数据的安全性较好,而GET较差;;
  3. POST发送数据不限制大小,而GET大小受限2~100k;
  4. POST发送的数据和GET发送的数据被请求地址接收到后显示的格式不一致;
  5. GET发送的数据被解析成key和value; POST发送的数据会被解析成字符串;
  6. get需要清除缓存,代码如下:ajaxGet(‘data/test.txt?t=’+ new Date().getTime(),fn)。

什么时候用GET和POST :在数据获取时用GET方式,在操作数据时应使用POST方式。

jsonp与get、post的区别

jsonp可以解决跨域:

  1. 当网站发展壮大到一定地步的时候,会建立很多的节点,各个节点的IP是不同的;
  2. 当测试阶段数据和本机的IP不通用的时候;
  3. 当本机请求服务器上数据的时候。

post和get只能解决本地服务器上的数据请求

后台的跨域解决方案:CORS跨域:
在php中加入以下两句就可以实现跨域访问
header(‘Access-Control-Allow-Origin:*’);//允许所有来源访问
header(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方式

get封装

		<input type="text" id="a">
		<input type="text" id="b">
		<input type="button" id="btn" value="发送">
		
	<script type="text/javascript">
			
		var oa = document.getElementById("a");
		var ob = document.getElementById("b");
		var obtn = document.getElementById("btn");	
		
		// obtn.onclick = function(){
		// 	var url = `http://localhost/ajax/data/get.php?user=${oa.value}&pass=${ob.value}`;
		// 	ajaxGet(url,function(res){
		// 		alert(res);
		// 	})
		// }
		
		//或
		
		obtn.onclick = function(){
			var url = `http://localhost/ajax/data/get.php`;
			ajaxGet(url,function(res){
				alert(res);
			},{
				user:oa.value,
				pass:ob.value
			})
		}
		function ajaxGet(url,cb,data){
			data = data || {};
			var str = "";
			for(var i in data){
				str += `${i}=${data[i]}&`
			}
			//设置时间戳,清楚缓存
			var d = new Date();
			//_wtt可任意设置
			url = url + "?" + str +"_wtt=" + d.getTime();
			//设置兼容,另一种适应IE5的基本上已经被淘汰
			var xhr = new XMLHttpRequest();
			xhr.open("get",url);
			xhr.onreadystatechange = function(){
			//4表示(完成)响应内容解析完成,可以在客户端调用了;200表示交易成功
				if(xhr.readyState == 4 && xhr.status == 200){
					cb(xhr.responseText)
				}
			}
			xhr.send();
		}	
	</script>
	//这是用来接收的php文件	
<?php
   $u = @$_GET["user"];
   $p = @$_GET["pass"];
   echo "这是php接收到的get的数据:".$u."----".$p;
?>	

注:
ajax的兼容问题:
ajax = new XMLHttpRequest();
ajax = new ActiveXObject(“Microsoft.XMLHTTP”); //IE5

post封装

		<input type="text" id="txt1">
		<input type="text" id="txt2">
		<input type="button" id="btn" value="发送">
	<script type="text/javascript">
		
		var otxt1 = document.getElementById("txt1")
		var otxt2 = document.getElementById("txt2")
		var obtn = document.getElementById("btn")
		
		obtn.onclick = function(){
			var url = "http://localhost/ajax/post.php";
			ajaxPost(url,function(res){
				console.log(res)
			})
		}
		
		function ajaxPost(url,cb){
			
			var xhr = new XMLHttpRequest();
			xhr.open("post",url)
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4 && xhr.status == 200){
			        cb(xhr.responseText);
			    }
			}
			//在发送数据之前ajax.send("user=admin"),设置请求头信息
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xhr.send();
		}
	</script>
	//这是来自url内的文件,也就是post.php内的代码	
<?php
    $u = @$_POST["user"];
    $p = @$_POST["pass"];
    echo "这是php接收到的post的数据:".$u."---".$p;
?>	

post在发送数据之前ajax.send(“user=admin”),设置请求头信息
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

jsonp的封装

	<script type="text/javascript">
	document.onclick = function(){
		var url = "http://127.0.0.1/jsonp/jsonp2.php";
		jsonp(url,function(res){
			console.log(res)
		},{
			user:"admin",
            pass:123,
            asd:"sadaasa",       //后台要执行的函数名
            cloumnName:"asd"  		//后台接收的要执行的函数名所在的字段名
		})
	}	
	function jsonp(url,success,data){
		
		data = data || {};
		var str = "";
		for(var i in data){
			str += `${i}=${data[i]}&`
		}
		url = url + "?" + str;
		
		var script = document.createElement("script");
		script.scr = url;
		document.body.appendChild(script);
		
		window[data[data.columnName]] = function(res){
			success(res)
		}
	}
	</script>	
	//这是url中的php代码	
	<?php
    $a = @$_GET["user"];
    $b = @$_GET["pass"];
    $cb = @$_GET["asd"];
    $data = "这是php通过jsonp接收到的跨域的数据,又还给你了:".$a."---".$b;
    echo $cb."('".$data."')";
	?>	

get与post二合一封装

	function ajxa(options){
		 // 解析参数,处理默认参数
		let {type,url,success,error,data} = options;
		type = type || "get";
		data = data || {};
		// 解析要发送的数据
		var str = "";
		for(var i in data){
			str += `${i}=${data[i]}&`;
		}
		
		if(type == "get"){
			var d = new Date();
			url = url + "?" + str + "_wtt=" + d.getTime();
		}
		
		var xhr = new XMLHttpRequest();
		xhr.open(type,url,true);
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				success(xhr.responseText)
			}else if(xhr.readyState == 4 && xhr.status != 200){
				error && error(xhr.status);
			}
		}
		
		if(type == "get"){
			xhr.send();
		}else if(type == "post"){
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xhr.send(str.slice(0,str.length-1));
		}
	}
<?php
	$u = @$_GET["user"];
    $p = @$_GET["pass"];
    echo "这是php接收到的数据:".$u."----".$p;
?>
<?php
	$u = @$_POST["user"];
    $p = @$_POST["pass"];
    echo "这是php接收到的post的数据:".$u."---".$p;
?>

get、post、jsonp三合一封装

function ajax(options){
    // 解析参数,处理默认参数
    let {type,url,success,error,data,timeout} = options;
    type = type || "get";
    data = data || {};
    timeout = timeout || 500;
    // 解析要发送的数据
    var str = "";
    for(var i in data){
        str += `${i}=${data[i]}&`;
    }
    // 处理url和数据
    if(type == "get" || type == "jsonp"){
        var d = new Date();
        url = url + "?" + str + "__qft=" + d.getTime();
    }
    
    // 区分jsonp和ajax的功能
    if(type === "jsonp"){
        var script = document.createElement("script");
        script.src = url;
        document.body.appendChild(script);

        window[data[data.columnName]] = function(res){
            success && success(res);
            error = null;
        }
        
        // jsonp的失败(超时)
        setTimeout(() => {
            error && error("timeout");
            success = null;
        }, timeout);
    }else{
        // 开启ajax
        var xhr = new XMLHttpRequest();
        xhr.open(type,url,true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                success(xhr.responseText);
            }else if(xhr.readyState == 4 && xhr.status != 200){
                // 首先保证ajax的过程结束了,如果http给失败,才是真正的失败
                error && error(xhr.status);
                // if(error) error(xhr.status);
            }
        }
        // 根据发送方式,决定发送的信息
        if(type == "get"){
            xhr.send()
        }else if(type == "post"){
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(str.slice(0,str.length-1));
        }
    }
}
<?php
	$u = @$_GET["user"];
    $p = @$_GET["pass"];
    echo "这是php接收到的get的数据:".$u."----".$p;
?>
<?php
	$u = @$_POST["user"];
    $p = @$_POST["pass"];
    echo "这是php接收到的post的数据:".$u."---".$p;
?>
<?php
	$a = @$_GET["user"];
    $b = @$_GET["pass"];
    $cb = @$_GET["callback"];
    $data = "这是php通过jsonp接收到的跨域的数据,又还给你了:".$a."----".$b;
    echo $cb."('".$data."')";
?>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值