Skip to content

原生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();
    			};
    		};
    	};
    }

}

天上的神明与星辰,人间的艺术和真纯,我们所敬畏和热爱的,莫过于此。