Home Web Front-end JS Tutorial Examples of secondary encapsulation jquery ajax method (graphic tutorial)

Examples of secondary encapsulation jquery ajax method (graphic tutorial)

May 22, 2018 am 10:32 AM
ajax jquery encapsulation

The full name of Ajax is Asynchronous JavaScript and XML. The following article mainly introduces you to examples of secondary encapsulation of jquery ajax. The article introduces it in detail through sample code. Friends who need it can follow it. Let’s take a look.

Preface

The full name of Ajax is Asynchronous JavaScript and XML Asynchronous javaScript and XML

AJax involves Obtained technology:

1. Use CSS and XHTML to express.

2. Use DOM model for interaction and dynamic display.

3. Use XMLHttpRequest to communicate asynchronously with the server. (Core)

4. Use javascript to bind and call.

When our front-end processes data, it is inevitable to communicate with ajax and the background. Ajax communicates with the server through the XMLHttpRequest object. jquery encapsulates the $.ajax method on the basis of XMLHttpRequest. Communication, $.ajax method is very practical and very simple to use. This second encapsulation of query ajax, refer to express to add middleware to process data, return Promise (Defferd) objects, reduce callbacks, and write ajax more concisely and elegantly.

$.ajax({
 url: url,
 data: data,
 dataType: 'json',
 type: 'get',
 success: new Function(){},
 error: new Function(){},
 .......
})
Copy after login

Most of the time we only need to pass in the url and data to get the data we want.

Pain Points

But when using $.ajax in the project, it still has some pain points

The data returned by ajax for basically all projects is now encapsulated twice, and the information in the background when processing business logic is added.

From returning data, it becomes {code: 200, data:{}, err_msg:''}

If every ajax request comes back, the code must be judged Whether it is correct before processing the business logic or reporting an error reminder, the entire project is too redundant.

$.ajax({
 url: url,
 data: data,
 success: function(data){
 if(data.code == 200) {
  dosomething()
 } else {
 alert(data.err_msg);
 }
 }
})
Copy after login

In order to solve this problem, we use a function to encapsulate $.ajax again, and put this This kind of correctness judgment is then processed and the business logic or error reminder is extracted and made into a public part.

util.ajax = function(obj, successFn){
 $.ajax({
 url: obj.url || '/interface',
 data: obj.data || {},
 dataType: obj.dataType || 'json',
 type: obj.type || 'get',
 success: function(data){
  if (data.code != 200) {
  alert(data.err_msg);
  } else {
  successFn(data.data)
  }
 },
 error: function(err){
  alert(err)
 }
 })
}
Copy after login

promise

Use util.ajax instead of $.ajax to reduce the It’s a wrong business judgment. Let's improve it again, instead of using callbacks, use promises to call, reducing callbacks and making the code clearer.

util.ajax = function(obj) {
 var deferred = $.Deferred();
 $.ajax({
  url: obj.url || '/interface',
  data: obj.data || {},
  dataType: obj.dataType || 'json',
  type: obj.type || 'get',
 }).success(function (data) {
  if (data.code != 200) {
   deferred.reject(data.err_msg);
  } else {
   deferred.resolve(data.data)
  }
 }).error(function (err) {
  deferred.reject('接口出错,请重试');
 })
 return deferred.fail(function (err) {
  alert(err)
 });
}


// 调用
var obj = {
 url: '/interface',
 data: {
  interface_name: 'name',
  interface_params: JSON.stringify({})
 }
};
util.ajax(obj)
 .done(function(data){
  dosomething(data)
 })
Copy after login

Middleware

This is a common method, but sometimes we need to deal with differentiation, we refer to express to introduce a middleware software to solve the differentiation problem.

util.ajax = function(obj, middleware) {
 var deferred = $.Deferred();
 $.ajax({
  url: obj.url || '/interface',
  data: obj.data || {},
  dataType: obj.dataType || 'json',
  type: obj.type || 'get',
 }).success(function (data) {
  if (data.code != 200) {
   deferred.reject(data.err_msg);
  } else {
   deferred.resolve(data.data)
  }
 }).error(function (err) {
  deferred.reject('接口出错,请重试');
 })

 // 添加中间件
 if(!middleware) {
  middleware = function(){};
 }
 return deferred.done(middleware).fail(function (err) {
  message({
   content: err,
   type: 'error',
   showLeftIcon: true,
   duration: 5000
  });
 });
}

// 调用
// 调用
var obj = {
 url: '/interface',
 data: {
  interface_name: 'name',
  interface_params: JSON.stringify({})
 }
};
var middleware = function(data) {
 data.forEach(function(item){
  item.fullName = item.firstName + item.lastName
 })
}
util.ajax(obj, middleware)
 .done(function(data){
  console.log(data.fullName)
 })
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

ajaxPerfect solution to cross-domain problems

Detailed analysis of the use of Ajax in JS Tips

JQuery calls Ajax to load images

The above is the detailed content of Examples of secondary encapsulation jquery ajax method (graphic tutorial). 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)

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

See all articles