基于$.ajax声明一个简单的AjaxHelper构造器,AjaxHelper构造器的原型对象包含5个方法,分别用于处理GET, POST, PUT, DELETE和JSONP
请求。
function AjaxHelper() { this.ajax = function(url, type, dataType, data, callback) { $.ajax({ url: url, type: type, dataType: dataType, data: data, success: callback, error: function(xhr, errorType, error) { alert('Ajax request error, errorType: ' + errorType + ', error: ' + error) } }) } } AjaxHelper.prototype.get = function(url, data, callback) { this.ajax(url, 'GET', 'json', data, callback) } AjaxHelper.prototype.post = function(url, data, callback) { this.ajax(url, 'POST', 'json', data, callback) } AjaxHelper.prototype.put = function(url, data, callback) { this.ajax(url, 'PUT', 'json', data, callback) } AjaxHelper.prototype.delete = function(url, data, callback) { this.ajax(url, 'DELETE', 'json', data, callback) } AjaxHelper.prototype.jsonp = function(url, data, callback) { this.ajax(url, 'GET', 'jsonp', data, callback) } AjaxHelper.prototype.constructor = AjaxHelper
发送get请求。实例:(vue实例)
var ajaxHelper = new AjaxHelper() var demo = new Vue({ el: '#app', data: { gridColumns: ['customerId', 'companyName', 'contactName', 'phone'], gridData: [], apiUrl: 'http://localhost:15341/api/Customers' }, ready: function() { this.getCustomers() }, methods: { getCustomers: function() { // 定义vm变量,让它指向this,this是当前的Vue实例 var vm = this, callback = function(data) { // 由于函数的作用域,这里不能用this vm.$set('gridData', data) } ajaxHelper.get(vm.apiUrl, null, callback) } } })
--纯原生js代码片段:
var ajax = function() {}; ajax.prototype = { request: function(method, url, callback, postVars) { var xhr = this.createXhrObject(); xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; (xhr.status === 200) ? callback.success(xhr.responseText, xhr.responseXML) : callback.failure(xhr,status); }; if (method !== "POST") { url += "?" + JSONStringify(postVars); postVars = null; } xhr.open(method, url, true); xhr.send(postVars); }, createXhrObject: function() { var methods = [ function() { return new XMLHttpRequest(); }, function() { return new ActiveXObject("Msxml2.XMLHTTP"); }, function() { return new ActiveXObject("Microsoft.XMLHTTP"); } ], i = 0, len = methods.length; for (; i < len; i++) { try { methods[i]; } catch(e) { continue; } this.createXhrObject = methods[i]; return methods[i]; } throw new Error("ajax created failure"); }, JSONStringify: function(obj) { return JSON.stringify(obj).replace(/"|{|}/g, "") .replace(/b:b/g, "=") .replace(/b,b/g, "&"); } };