原生js實現ajax方法

var Ajax={
	    get: function(url, fn) {
	        var xhr = new XMLHttpRequest();        
	        xhr.open('GET', url, true);
	        xhr.onreadystatechange = function() {
	            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
	                fn.call(this, xhr.responseText);
	            }
	        };
	        xhr.send();
	    },
    	post: function (url, data, fn) {
	        var xhr = new XMLHttpRequest();
	        xhr.open("POST", url, true);
	        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
	        xhr.onreadystatechange = function() {
	            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
	                fn.call(this, xhr.responseText);
	            }
	        };
	        xhr.send(data);
    	}
	};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章