Home  >  Article  >  Web Front-end  >  How to write ajax requests with the highest performance in jQuery

How to write ajax requests with the highest performance in jQuery

php中世界最好的语言
php中世界最好的语言Original
2018-03-15 15:05:171069browse

This time I will bring you how to write ajax requests with the highest performance in jQuery and how to write ajax requests with the highest performance in jQuery. What are the precautions?. Here are practical cases. Let’s take a look. one time.

Preface

jQuery is indeed a very good lightweight JS framework that can help us quickly develop JS applications and To a certain extent, it has changed our habit of writing JavaScript code.

Without further ado, let’s get straight to the point. jQuery’s ajax method is very easy to use. With such a good thing, do you want to have your own ajax? Next, let’s make a simple ajax ourselves.

First you need a configuration file

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'
  }
 ]
}

Then you need a method to generate an interface from the configuration file

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();
}

Try it out

<!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>

Advantages and extensions

[Advantages]: Similar Callback method with promise

[Advantages]: Adding an interface only requires adding a configuration file, which is very convenient

[Extension]: I only wrote json for the current ajax contentType, if you are interested Can extend other data types

[Disadvantages]: No verification of function parameters

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How two zTree interact with each other

How to use webpack to write jquery environment configuration

How to automatically convert uppercase and lowercase letters when jackson parses a json string

Usage of jQuery EasyUI folding panel

The above is the detailed content of How to write ajax requests with the highest performance in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn