原生JS写的Ajax封装函数

I forgot the source of the following code snippet, maybe it is from a book named Learning from jQuery


var ajax = function(url, fnSuccess, fnFailed) {
	//create oAjax object
	var oAjax;
	if(window.XMLHttpRequest) {
		oAjax = new XMLHttpRequest();
	}else {
		oAjax = new ActiveXObject("Microsoft.XMLHTTP");
	}

	//connect to the server
	oAjax.open("GET", url, true); //open("POST" or "GET" method, url, 是否异步加载)

	//send the request
	oAjax.send();

	//receive the reply from the server side
	oAjax.onreadystatechange = function() {
		if (oAjax.readyState ==4) { //4 indicates job finished
			if (oAjax.status == 200) { //200 indicates job finished successfully 
				fnSuccess(oAjax.responseText);
			} else{
				if (fnFailed) {
					fnFailed();
				};
			};
		};
	}
}
Author: Yakima
关于作者:楠溪江人,出生于1991年,目前坐标上海。读书时代跳过级、保过送,工作后转过行。2013年本科毕业于北药。看书、码字、敲代码、打羽毛球是我花时间的爱好。曾在某上市药企任国际药品注册岗,现在某高新企业任前端管理岗。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据