Home Web Front-end JS Tutorial Code examples of jquery ajax method encapsulation and api file design

Code examples of jquery ajax method encapsulation and api file design

Mar 27, 2019 am 09:13 AM
javascript

本篇文章给大家带来的内容是关于jquery ajax方法封装及api文件设计的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

封装 jquery ajax 文件

/**
 * 封装 jquery ajax 
 * 例如:
 * ajaxRequest.ajax.triggerService(
 *   'apiCommand', [命令数据] )
 *   .then(successCallback, failureCallback);
 * );
 */
var JSON2 = require('LibsDir/json2');
var URL = '../AjaxHandler.aspx?r=';

// 用来记录每次请求的唯一标识
var requestIdentifier = {};

// 唯一标识生成方法
function generateGUID() {
  var d = new Date().getTime();
  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
    d += performance.now();
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}

// 模块主体
var ajaxRequest = ajaxRequest || {};
(function ($) {
  if (!$) {
    throw 'jquery获取失败!';
  }

  ajaxRequest.json = JSON2;
  ajaxRequest.ajax = function (userOptions, serviceName, requestId) {
    userOptions = userOptions || {};
    var options = $.extend({}, ajaxRequest.ajax.defaultOpts, userOptions);
    options.success = undefined;
    options.error = undefined;
    return $.Deferred(function ($dfd) {
      $.ajax(options)
        .done(function (result, textStatus, jqXHR) {
          if (requestId === requestIdentifier[serviceName]) {
            // 比对请求id, 保证返回结果的正确性 (重复请求有可能会带来返回结果不可靠的问题)
            ajaxRequest.ajax.handleResponse(result, $dfd, jqXHR, userOptions, serviceName, requestId);
          }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          if (requestId === requestIdentifier[serviceName]) {
            // jqXHR.status
            $dfd.reject.apply(this, arguments);
            userOptions.error.apply(this, arguments);
          }
        });
    });
  };

  $.extend(ajaxRequest.ajax, {
    // $.ajax() 的默认设置
    defaultOpts: {
      // url: '../AjaxSecureHandler.aspx,
      dataType: 'json',
      type: 'POST',
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
    },

    handleResponse: function (result, $dfd, jqXHR, userOptions, serviceName, requestId) {
      if (!result) {
        $dfd && $dfd.reject(jqXHR, 'error response format!');
        userOptions.error(jqXHR, 'error response format!');
        return;
      }

      // 服务器已经错误
      if (result.ErrorCode != '200') {
        $dfd && $dfd.reject(jqXHR, result.ErrorMessage);
        userOptions.error(jqXHR, result);
        return;
      }

      if (result.Data) {
        // 将大于2^53的数字(16位以上)包裹双引号, 避免溢出
        var jsonStr = result.Data.replace(/(:\s*)(\d{16,})(\s*,|\s*})/g, '$1"$2"$3');
        var resultData = ajaxRequest.json.parse(jsonStr);
        $dfd.resolve(resultData);
        userOptions.success && userOptions.success(resultData);
      } else {
        $dfd.resolve();
        userOptions.success && userOptions.success();
      }
    },

    buildServiceRequest: function (serviceName, input, userSuccess, userError, ajaxParams) {
      // 这里是根据后台要求构建的
      var requestData = {
        MethodAlias: serviceName, // 方法名
        Parameter: input // 传递的参数
      };

      var request = $.extend({}, ajaxParams, {
        // 这里要对传递的 JSON 字符串参数数据使用 escape 方法进行编码
        // 'data=' 是根据项目约定增加的,与 contentType 相对应
        data: 'data=' + escape(ajaxRequest.json.stringify(requestData)),
        success: userSuccess,
        error: function (jqXHR, textStatus, errorThrown) {
          // 这里是在请求出错的时候做一个统一处理, 输出方法名和错误对象
          console.log(serviceName, jqXHR);
          if (userError && (typeof userError === 'function')) {
            userError(jqXHR, textStatus, errorThrown);
          }
        }
      });

      return request;
    },

    // 构建参数对象, 生成唯一标识, 触发请求
    triggerService: function (serviceName, input, success, error, ajaxParams) {
      var request = ajaxRequest.ajax.buildServiceRequest(serviceName, input, success, error, ajaxParams);
      // 生成此次 ajax 请求唯一标识
      var requestId = requestIdentifier[serviceName] = generateGUID();
      request.url = URL + requestId;
      return ajaxRequest.ajax(request, serviceName, requestId);
    }
  });

})(jQuery);

module.exports = ajaxRequest;
Copy after login

api 文件示例

/**
 * api 接口定义
 * 这个示例中假设后台服务要求接受数组形式的参数
 */
var ajaxRequest = require('../common/ajax-request'); // ajax 封装
var JSON2 = require('LibsDir/json2');

// 请求数据方法
var apiService = (function () {
  var request = {};
  // 产品列表 (参数需要进一步处理的情况)
  request.getProductListData = function (conditionObj) {
    return ajaxRequest.ajax.triggerService('SearchProductList', [JSON2.stringify(conditionObj)]);
  };

  // 搜索热词 (参数为空的情况)
  request.getHotWords = function () {
    return ajaxRequest.ajax.triggerService('GetSearchHotKeys', []);
  };

  // 获取用户配置
  request.getUserConfig = function () {
    return ajaxRequest.ajax.triggerService('GetUserConfig', []);
  };

  // 设置用户配置
  request.setUserConfig = function (params) {
    return ajaxRequest.ajax.triggerService('SetUserConfig', [params]);
  };

  return request;
})();

module.exports = apiService;
Copy after login

业务代码中调用 api 接口

// 综合搜索热词查询
apiService.getHotWords()
  .then(function (result) {
    if (result.length > 0) {
      // 成功回调
      // handleResult(result);
    }
  })
  .fail(function (err) {
    console.log('GetSearchHotKeys: ', err);
    // 失败回调
    handleResult();
  });
Copy after login

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

The above is the detailed content of Code examples of jquery ajax method encapsulation and api file design. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles