zl程序教程

您现在的位置是:首页 >  前端

当前栏目

jQuery的ajax巧妙利用详解编程语言

jQueryAJAX编程语言 详解 利用 巧妙
2023-06-13 09:20:43 时间

jQuery的ajax巧妙利用详解编程语言


一.首先需要一个配置文件

var api = {

  basePath: http://192.168.0.1:8081 ,

  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

  });

  },

  /**

  * 主要用于将 /users/{{userId}} 和{userId: 89898 }转换成/users/89898,和mastache语法差不多,

  * 当然我们没必要为了这么小的一个功能来引入一个模板库query字符串可以当做一个参数传递进来

  */

  render: function(tpl, data){

  var re = /{{([^}]+)?}}/g;

  var match =

  while(match = re.exec(tpl)){

  tpl = tpl.replace(match[0],data[match[1]]);

  }

  return tpl;

  }

};

/**

 * 设置头部信息的方法

 * 有些方法需要特定的头部信息,例如登录之后才能获取sesssionId,然后访问所有的接口时,必须携带sessionId才可以访问

 */

Api.pt.setHeader = function(headers){

  headers = headers;

};

/**

 * 发送ajax请求,this会绑定到每个接口上

 */

function fire(pathParm, payload){

  var url = util.render(this.path, pathParm);

  return util.ajax(url, this.method, payload);

}

/**

 * 遍历所有接口

 */

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:
[email protected] })

  .done(function(res){

  console.log( 成功 );

  })

  .fail(function(res){

  console.log( 失败 );

  });

/script

/body

/html


四.优点

   1.类似与promise的回调方式

   2.增加一个接口只是需要增加一个配置文件,很方便


五.扩展

   1.当前的ajax 的contentType我只写了json,有兴趣可以扩展其他的数据类型


六.缺点

   1.没有对函数参数进行校验

jQuery的ajax巧妙利用详解编程语言

转载请注明来源网站:blog.ytso.com谢谢!

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14950.html

cjava