自定义AJAX

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<script>
		/*
			自定义AJAX
			当data传送文件时 contentType 需设置 false (不需要头部申明)
			ajax(访问地址,{
				type: "post",
				data:{
					id: 123
					},
				contentType: false,
				success: function(data){
					console.log(data);
					},
				error: function(){}
			});			
		*/
		function ajax(url, options) {
			options = options || {};
			options.type = (options.type || "GET").toUpperCase();
			options.dataType = options.dataType || "JSON";
			var params = formatParams(options.data);

			function formatParams(obj) {
				var isJson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" &&
					!obj.length;
				if (isJson) {
					var arr = [];
					for (var name in obj) {
						arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(obj[name]));
					}
					arr.push(("v=" + Math.random()).replace(".", "a").replace("1", "b").replace("3", "c").replace("5", "d").replace(
						"7", "e").replace("9", "k"));
					return arr.join("&");
				} else {
					return obj;
				}
			}
			var xhr;
			if (win.XMLHttpRequest) {
				xhr = new XMLHttpRequest();
			} else if (win.ActiveXObject("Microsoft.XMLHTTP")) {
				xhr = new ActiveXObject('Microsoft.XMLHTTP');
			}
			if (options.type == "GET") {
				xhr.open("GET", url + "?" + params, true);
				xhr.send(null);
			} else if (options.type == "POST") {
				xhr.open("POST", url, true);
				if (!options.contentType && options.contentType != false) {
					xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				}
				xhr.send(params);
			}
			xhr.onreadystatechange = function () {
				if (xhr.readyState == 4) {
					var status = xhr.status;
					if (status >= 200 && status < 300 || status == 304) {
						typeof xhr.responseText === "string" && options.success && options.success(eval('(' + xhr.responseText + ')'),
							xhr.responseXML);
					} else {
						options.error && options.error(status);
					};
				}
			};
		}
	</script>
</body>

</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值