jQuery進階:用最優雅的方式寫ajax請求
首先需要一個配置文件
var api = {
basePath: 'http://192.168.200.226:58080',
pathList: [
{
name: 'agentHeartBeat',
path:'/api/csta/agent/heartbeat/{{agentId}}',
method:'post'
},
{
name: 'setAgentState',
path: '/api/csta/agent/state',
method: 'post'
},
{
name: 'getAgents',
path: '/user/agent/{{query}}',
method: 'get'
}
]
}
然后需要一個方法,把配置文件生成接口
function WellApi(Config){
var headers = {};
var Api = function(){};
Api.pt = Api.prototype;
var util = {
ajax: function(url, method, payload) {
return $.ajax({
url: url,
type: method || "get",
data: JSON.stringify(payload),
headers: headers,
dataType: "json",
contentType: 'application/json; charset=UTF-8'
});
},
/**
* [render 模板渲染]
* 主要用于將 /users/{{userId}} 和{userId: '89898'}轉換成/users/89898,和mastache語法差不多,
* 當然我們沒必要為了這么小的一個功能來引入一個模板庫
* query字符串可以當做一個參數傳遞進來
* 例如: /users/{{query}}和{query:'?name=jisika&sex=1'}
* @Author Wdd
* @DateTime 2017-03-13T19:42:58+0800
* @param {[type]} tpl [description]
* @param {[type]} data [description]
* @return {[type]} [description]
*/
render: function(tpl, data){
var re = /{{([^}]+)?}}/g;
var match = '';
while(match = re.exec(tpl)){
tpl = tpl.replace(match[0],data[match[1]]);
}
return tpl;
}
};
/**
- [setHeader 暴露設置頭部信息的方法]
- 有些方法需要特定的頭部信息,例如登錄之后才能獲取sesssionId,然后訪問所有的接口時,必須攜帶sessionId
- 才可以訪問
- @Author Wdd
- @DateTime 2017-03-13T10:34:03+0800
- @param {[type]} headers [description]
*/
Api.pt.setHeader = function(headers){
headers = headers;
};
/**
- [fire 發送ajax請求,this會綁定到每個接口上]
- @Author Wdd
- @DateTime 2017-03-13T19:42:13+0800
- @param {[type]} pathParm [description]
- @param {[type]} payload [description]
- @return {[type]} [description]
*/
function fire(pathParm, payload){
var url = util.render(this.path, pathParm);
return util.ajax(url, this.method, payload);
}
/**
- [for 遍歷所有接口]
- @Author Wdd
- @DateTime 2017-03-13T19:49:33+0800
- @param {[type]} var i [description]
@return {[type]} [description]
*/
for(var i=0; i < Config.pathList.length; i++){
Api.pt[Config.pathList[i].name] = {
path: Config.basePath + Config.pathList[i].path,
method: Config.pathList[i].method,
fire: fire
};
}
return new Api();
}</code></pre>
試用一下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src=";
<script src="api.js"></script>
<script src="jquery-ajax.js"></script>
</head>
<body>
<script type="text/javascript">
var saas = WellApi(api);
saas.agentHeartBeat.fire({agentId: '5001@1011.cc'})
.done(function(res){
console.log('心跳成功');
})
.fail(function(res){
console.log('心跳失敗');
});
</script>
</body>
</html></code></pre>
優點與擴展
-
[優點]:類似與promise的回調方式
-
[優點]:增加一個接口只是需要增加一個配置文件,很方便
-
[擴展]:當前的ajax 的contentType我只寫了json,有興趣可以擴展其他的數據類型
-
[缺點]:沒有對函數參數進行校驗
來自:https://segmentfault.com/a/1190000008678653