最近回顾一下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; })();