函数封装--原生ajax调用接口

本文介绍了一种自定义实现AJAX请求的方法,包括GET和POST请求方式,并支持JSONP跨域请求。提供了完整的函数代码及请求示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function ajax(options) {
	function setData() {
		function setObjData(data, parentName) {
			function encodeData(name, value, parentName) {
				var items = [];
				name = parentName === undefined ? name : parentName + "[" + name + "]";
				if (typeof value === "object" && value !== null) {
					items = items.concat(setObjData(value, name));
				} else {
					name = encodeURIComponent(name);
					value = encodeURIComponent(value);
					items.push(name + "=" + value);
				}
				return items;
			}
			var arr = [], value;
			if (Object.prototype.toString.call(data) == '[object Array]') {
				for (var i = 0, len = data.length; i < len; i++) {
					value = data[i];
					arr = arr.concat(encodeData(typeof value == "object" ? i : "", value, parentName));
				}
			} else if (Object.prototype.toString.call(data) == '[object Object]') {
				for (var key in data) {
					value = data[key];
					arr = arr.concat(encodeData(key, value, parentName));
				}
			}
			return arr;
		};
		function setStrData(data) {
			var arr = data.split("&");
			for (var i = 0, len = arr.length; i < len; i++) {
				name = encodeURIComponent(arr[i].split("=")[0]);
				value = encodeURIComponent(arr[i].split("=")[1]);
				arr[i] = name + "=" + value;
			}
			return arr;
		}
		if (data) {
			if (typeof data === "string") {
				data = setStrData(data);
			} else if (typeof data === "object") {
				data = setObjData(data);
			}
			data = data.join("&").replace("/%20/g", "+");
			//若是使用get方法或JSONP,则手动添加到URL中
			if (type === "get" || dataType === "jsonp") {
				url += url.indexOf("?") > -1 ? (url.indexOf("=") > -1 ? "&" + data : data) : "?" + data;
			}
		}
	}
	function createJsonp() {
		var script = document.createElement("script"),
			timeName = new Date().getTime() + Math.round(Math.random() * 1000),
			callback = "JSONP_" + timeName;

		window[callback] = function (data) {
			clearTimeout(timeout_flag);
			document.body.removeChild(script);
			success(data);
		}
		script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + "callback=" + callback;
		script.type = "text/javascript";
		document.body.appendChild(script);
		setTime(callback, script);
	}
	function setTime(callback, script) {
		if (timeOut !== undefined) {
			timeout_flag = setTimeout(function () {
				if (dataType === "jsonp") {
					delete window[callback];
					document.body.removeChild(script);

				} else {
					timeout_bool = true;
					xhr && xhr.abort();
				}
				console.log("timeout");

			}, timeOut);
		}
	}
	function createXHR() {
		function getXHR() {
			if (window.XMLHttpRequest) {
				return new XMLHttpRequest();
			} else {
				var versions = ["Microsoft", "msxm3", "msxml2", "msxml1"];
				for (var i = 0; i < versions.length; i++) {
					try {
						var version = versions[i] + ".XMLHTTP";
						return new ActiveXObject(version);
					} catch (e) { }
				}
			}
		}
		xhr = getXHR();
		xhr.open(type, url, async);
		if (type === "post" && !contentType) {
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		} else if (contentType) {
			xhr.setRequestHeader("Content-Type", contentType);
		}
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4) {
				if (timeOut !== undefined) {
					if (timeout_bool) {
						return;
					}
					clearTimeout(timeout_flag);
				}
				if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {

					success(xhr.responseText);
				} else {
					error(xhr.status, xhr.statusText);
				}
			}
		};
		xhr.send(type === "get" ? null : data);
		setTime();
	}
	var url = options.url || "",
		type = (options.type || "get").toLowerCase(),
		data = options.data || null,
		contentType = options.contentType || "",
		dataType = options.dataType || "",
		async = options.async === undefined ? true : options.async,
		timeOut = options.timeOut,
		before = options.before || function () { },
		error = options.error || function () { },
		success = options.success || function () { };
	var timeout_bool = false,
		timeout_flag = null,
		xhr = null;
	setData();
	if (dataType === "jsonp") {
		createJsonp();
	} else {
		createXHR();
	}
}
请求示例:
get:
	ajax({
		type: "get",
		url: "http://apis.juhe.cn/springTravel/risk?key=33964fc2da441b312b0ab610228c060d",

		before() {
			console.log("before");
		},
		success(res) {
			console.log("get疫情", res);
		},
		error() {
			console.log("err");
		},
		dataType: "jsonp",
		timeOut: 5000,
	});


post:
	ajax({
		type: "post",
		url: "http://apis.juhe.cn/springTravel/risk",
		dataType: "jsonp",
		data:{key:"33964fc2da441b312b0ab610228c060d"},
		timeOut: 5000,
		before() {
			console.log("before");
		},
		success(res) {
			console.log("post疫情", res);
		},
		error() {
			console.log("err");
		}
	});

参数表:
| 参数 | 默认值 | 描述 | 可选值 |
|:----|:----|:----|:----|
| url | "" | 请求的链接 | string |
| type | get | 请求的方法 | get,post |
| data | null | 请求的数据 | object,string |
| contentType | "" | 请求头 | string |
| dataType | "" | 请求的类型 | jsonp |
| async | true | 是否异步 | blooean |
| timeOut | undefined | 超时时间 | number |
| before | function(){} | 发送之前执行的函数 | function |
| error | function(){} | 请求报错执行的函数 | function |
| success | function(){} | 请求成功的回调函数 | function |

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值