Faster, Higher, Stronger
更快,更高,更强

原生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();
				};
			};
		};
	}
}
赞(0) 打赏
未经允许不得转载:峰间的云 » 原生JS写的Ajax封装函数

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏