Last active
June 3, 2016 08:41
-
-
Save kevinma2010/0213bfea8e3f08ff8d66 to your computer and use it in GitHub Desktop.
基于 jQuery Ajax 定制自己喜爱的 API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//附加公共参数 | |
$http.global("token","abcd321"); | |
$http.use("/api", function (res) { | |
if (res.success) { | |
return true; | |
} | |
var err = res.error; | |
if (err.code === 1001) { | |
location.href = "/login.html"; | |
} else { | |
alert(err.message); | |
} | |
return false; | |
}); | |
$http.get("/api/user") | |
.type("json") | |
.param("id", 110) | |
.send(function (res) { | |
// 过滤器处理完才会执行到这一步 | |
var datum = res.datum; | |
alert("Name: " + datum.name); | |
console.log(res.datum); | |
}, function (err) { | |
alert("查询失败了额"); | |
console.error(err); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Longbo Ma | |
*/ | |
(function ($) { | |
var _Http = {}, | |
globalData = {},// 全局数据, 请求时会发送 | |
handlers = {}, // 过滤器 | |
interceptors = [] //全局拦截器; | |
/** | |
* 合并数据 | |
* @param global | |
* @param data | |
* @returns {*} | |
*/ | |
function merge(global,data) { | |
if (!data) return copy(global,{}); | |
var result = copy(global,{}); | |
return copy(data,result); | |
} | |
/** | |
* copy json对象数据 | |
* @param s 源对象 | |
* @param t 目的对象 | |
* @returns {*} | |
*/ | |
function copy (s,t) { | |
for (var key in s) { | |
t[key] = s[key]; | |
} | |
return t; | |
} | |
/** | |
* 将普通数组转化为json对象,json key为数组项值 | |
* 方便判断 | |
* @param arr | |
* @returns {{}} | |
*/ | |
function toJsonArr(arr) { | |
var json = {}; | |
for (var i = 0, total = arr.length; i < total; i++) { | |
json[arr[i]] = ""; | |
} | |
return json; | |
} | |
/** | |
* 检测json数组中是否包含某个值 | |
* @param jsonArr 该值必须是从toJsonArr函数得来的 | |
* @param val 要检查的值 | |
* @returns {*|boolean} 结果 | |
*/ | |
function contain(jsonArr,val) { | |
return jsonArr.hasOwnProperty(val); | |
} | |
/** | |
* Ajax请求对象 | |
* @param method 请求类型 | |
* @param url 请求链接 | |
* @param data 发送的数据 json对象or拼接的string数据 | |
* @constructor | |
*/ | |
var Request = function (method,url,data) { | |
this.method = method; | |
this.url = url; | |
this.data = data || {}; | |
this.headers = []; | |
}; | |
/** | |
* 设置响应数据类型 | |
* @param type 字符串"json"/"xml"等 | |
* @returns {Request} | |
*/ | |
Request.prototype.type = function (type) { | |
this.type = type; | |
return this; | |
}; | |
/** | |
* 设置是否为异步请求 | |
* @param async Boolean,默认为true | |
* @returns {Request} | |
*/ | |
Request.prototype.async = function (async) { | |
this.async = async; | |
return this; | |
}; | |
/** | |
* 设置是否开启浏览器缓存,默认: true, dataType为"script"和"jsonp"时默认为false | |
* @param cache Boolean | |
* @returns {Request} | |
*/ | |
Request.prototype.cache = function (cache) { | |
this.cache = cache; | |
return this; | |
}; | |
/** | |
* 设置请求超时时间(毫秒) | |
* @param timeout Number | |
* @returns {Request} | |
*/ | |
Request.prototype.timeout = function (timeout) { | |
this.timeout = timeout; | |
return this; | |
}; | |
/** | |
* 设置发送的数据,将覆盖已设置的数据 | |
* @param data json对象or拼接的string数据 | |
* @returns {Request} | |
*/ | |
Request.prototype.params = function (data) { | |
this.data = data; | |
return this; | |
}; | |
/** | |
* 设置新发送的数据 | |
* @param key 参数名/json object | |
* @param value 参数值 | |
* @returns {Request} | |
*/ | |
Request.prototype.param = function (key, value) { | |
if (!key || !value) return; | |
try { | |
JSON.stringify(key); | |
copy(key, this.data); | |
} catch (err) { | |
this.data[key] = value; | |
} | |
return this; | |
}; | |
/** | |
* set headers | |
* @param {[json object]} headers | |
* @return {[Request]} | |
*/ | |
Request.prototype.headers = function (headers) { | |
this.headers = headers; | |
return this; | |
}; | |
/** | |
* push header item | |
* @param {[String,JSON]} key | |
* @param {[String,null]} value | |
* @return {[Request]} | |
*/ | |
Request.prototype.header = function (key, value) { | |
if (!key || !value) return; | |
try { | |
JSON.stringify(key); | |
copy(key, this.headers); | |
} catch (err) { | |
this.headers[key] = value; | |
} | |
return this; | |
}; | |
/** | |
* execute interceptors | |
* @param {[type]} res [description] | |
*/ | |
Request.prototype.execuHandlers = function (res) { | |
if (this.type !== "json") { | |
this.success(res); | |
return; | |
} | |
for(var key in handlers) { | |
if (this.url.startsWith(key)) { | |
for (var i = 0; i < handlers[key].length; i++) { | |
var fn = handlers[key][i]; | |
var invoke = fn(res); | |
//检查结果,决定是否继续执行其他拦截器 | |
if (invoke !== undefined && !invoke) { | |
return; | |
} | |
} | |
} | |
} | |
this.success(res); | |
}; | |
/** | |
* 发送请求 | |
* @param success 成功响应回调函数 | |
* @param error 错误处理回调函数 | |
*/ | |
Request.prototype.send = function (success, error) { | |
var self = this; | |
var param = { | |
url: this.url, | |
type: this.method | |
}; | |
//设置响应数据类型 | |
if (this.type) { | |
param.dataType = this.type; | |
} | |
//设置发送数据 | |
if (this.data && typeof this.data !== 'function') { | |
param.data = this.data; | |
} | |
//set headers | |
if (this.headers && typeof this.headers !== 'function' && JSON.stringify(this.headers).length > 2)) { | |
param.headers = this.headers; | |
} | |
//设置成功响应回调函数 | |
if (success && typeof success === 'function') { | |
this.success = success; | |
param.success = function (res) { | |
self.execuHandlers.call(self, res); | |
}; | |
} | |
//设置错误响应回调函数 | |
if (error && typeof error === 'function') { | |
this.error = error; | |
param.error = function (err) { | |
//正确的请求响应 | |
if (err.status === 200 && err.statusText === "OK") { | |
var response = err.responseText; | |
//如果是json数据,则转化为json对象 | |
try { | |
response = JSON.parse(response); | |
} catch (parseError) { | |
response = err.responseText; | |
} | |
self.execuHandlers.call(self, response); | |
} else { | |
error(err); | |
} | |
}; | |
} | |
$.ajax(param); | |
}; | |
/** | |
* 发送 POST 请求 | |
* @param url 请求地址 | |
* @param data 请求数据,json或拼接的字符串 | |
* @returns {Request} 请求对象 | |
*/ | |
_Http.post = function (url,data) { | |
return new Request("POST",url,merge(globalData,data)); | |
}; | |
/** | |
* 发送 PUT 请求 | |
* @param url 请求地址 | |
* @param data 请求数据,json或拼接的字符串 | |
* @returns {Request} 请求对象 | |
*/ | |
_Http.put = function (url,data) { | |
return new Request("PUT",url,merge(globalData,data)); | |
}; | |
/** | |
* 发送 GET 请求 | |
* @param url 请求地址 | |
* @param data 请求数据,json或拼接的字符串 | |
* @returns {Request} 请求对象 | |
*/ | |
_Http.get = function (url,data) { | |
return new Request("GET",url,merge(globalData,data)); | |
}; | |
/** | |
* 发送 GET 请求 | |
* @param url 请求地址 | |
* @param data 请求数据,json或拼接的字符串 | |
* @returns {Request} 请求对象 | |
*/ | |
_Http.getJson = function (url,data) { | |
return new Request("GET",url,merge(globalData,data)).type("json"); | |
}; | |
/** | |
* 发送 DELETE 请求 | |
* @param url 请求地址 | |
* @param data 请求数据,json或拼接的字符串 | |
* @returns {Request} 请求对象 | |
*/ | |
_Http.del = function (url,data) { | |
return new Request("DELETE",url,merge(globalData,data)); | |
}; | |
/** | |
* 设置公共附加请求参数 | |
* @param name string or jsonObject | |
* @param value | |
*/ | |
_Http.global = function (name, value) { | |
if (!name || !value) return; | |
try { | |
JSON.stringify(name); | |
copy(name, globalData); | |
} catch (err) { | |
globalData[name] = value; | |
} | |
return _Http; | |
}; | |
/** | |
* 新增一个拦截器,暂时只支持JSON类型的数据响应 | |
* @param fn | |
*/ | |
_Http.use = function (urlPrefix,fn) { | |
urlPrefix = urlPrefix || "/"; | |
var _handlers = handlers[urlPrefix] || []; | |
_handlers.push(fn); | |
handlers[urlPrefix] = _handlers; | |
return _Http; | |
}; | |
this.$http = _Http; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment