当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery进阶实践之利用最优雅的方式如何写ajax请求

jQuery进阶实践之利用最优雅的方式如何写ajax请求

2018年02月21日  | 移动技术网IT编程  | 我要评论

前言

jquery确实是一个挺好的轻量级的js框架,能帮助我们快速的开发js应用,并在一定程度上改变了我们写javascript代码的习惯。

废话少说,直接进入正题,jquery的ajax方法非常好用,这么好的东西,你想拥有一个属于自己的ajax么?接下来,我们来自己做一个简单的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 = /{{([^}]+)?}}/;
  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();
}

试用一下

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
  <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>

优点与扩展

[优点]:类似与promise的回调方式

[优点]:增加一个接口只是需要增加一个配置文件,很方便

[扩展]:当前的ajax 的contenttype我只写了json,有兴趣可以扩展其他的数据类型

[缺点]:没有对函数参数进行校验

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网