ajax的js插件封装

来源:互联网 发布:crossgear 知乎 编辑:程序博客网 时间:2024/06/07 18:13

最近回顾一下ajax,ajax使用并不难,下面对ajax简单封装,方便以后使用:

window.onload = function() {new Ajax({method: 'GET',//传输方式url: 'data_handle.php',//数据文件data: 'name=dalin&age=23',//发送数据,可选succee: function(data) {//返回数据为字符串,需要转换为json格式alert(data);},fail: function(error) {alert('无法获取数据' + error);}});};(function() {function Ajax(o) {this.config = o;var that = this;this.XHR = new XMLHttpRequest();this.requestFn();this.XHR.onreadystatechange = function() {that.stateFn();}}Ajax.prototype.requestFn = function() {if(this.config.data && this.config.method.toLowerCase() == 'get') {var url = this.config['url'] + '?' + this.config.data;} else {var url = this.config['url'] + '?a=' + Math.random();}this.XHR.open(this.config.method, url, true);if(this.config.data && this.config.method.toLowerCase() == 'post') {this.XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');this.XHR.send(this.config.data);} else {this.XHR.send(null);}}Ajax.prototype.stateFn = function() {if(this.XHR.readyState == 4) {if(this.XHR.status == 200) {return this.config.succee(this.XHR.responseText);} else {return this.config.fail(this.XHR.statusText);}}}window.Ajax=Ajax;})();


0 0