Encapsulation of ajax method based on jQuery

  • 2021-07-02 23:32:24
  • OfStack

Brief introduction of ajax (ajax development)

AJAX is "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), which refers to a web page development technology for creating interactive web page applications.

AJAX = asynchronous JavaScript and XML (a subset of the Standard Generalized Markup Language).

AJAX is a technology for creating fast dynamic web pages.

AJAX enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that you can update parts of the page without reloading the entire page.

In actual projects, ajax is used very frequently, so although jquery or other similar js libraries have done very good packaging, there is still room and necessity for further packaging and simplification

For example, a long, long time ago, my ajax wrote this:


$.ajax({
url: 'www.baidu.com/getInfo',
type: 'POST',
data: {
name: 'jack',
age: 18
},
dataType: 'json',
success: function(resp){
// callback
},
error: function(err){
// error code
} 
});

At first glance, it looks good and there is no problem, but in fact, the logic in the success callback may be very complicated, and there may even be another ajax in the ajax callback, so this writing is very bad, all mixed in one case

You can do a simple encapsulation, which was mentioned in the essay on Deferred object before


function ajax(url, param, type) {
//  Take advantage of jquery The way to delay object callbacks is similar to the ajax Encapsulate, use done() , fail() , always() And other methods to carry out chain callback operation 
//  If you need more parameters, such as cross-domain dataType Need to be set to 'jsonp' And so on, you can consider setting the parameter to an object 
return $.ajax({
url: url,
data: param || {},
type: type || 'GET'
});
}
//  Chain callback 
ajax('www.baidu.com/getInfo').done(function(resp) {
//  Successful callback 
}).fail(function(err) {
//  Failed callback 
});

However, although this step has been achieved, problems will still come. For example, in our company, there is still one layer of logical judgment in the successful callback, like this:


//  Our company ajax Returned json Data format 
//  When result For false When, msg There are often error messages in 
{
result: true,
data: {
name: 'jack'
},
msg: null
}
ajax('www.baidu.com/getInfo').done(function(resp) {
//  Successful callback 
if(resp.result){
//  When resp Medium result For true Operation when 
//  It is often necessary to operate and process at this time resp In data Object information 
}
else{
//  When result For false At this time, it is often based on the operation of resp Another in 1 Attribute msg To judge the specific treatment 
}
}).fail(function(err) {
//  Failed callback 
});

There are two questions:

First, I need to write the same relatively fixed logical judgment in every ajax (each company or project team may be different, but it must be fixed in terms of the project itself or enlarged to the company), which makes me feel very annoyed.

Second, if I only want to focus on processing data, for example, in a successful callback, I directly get the data to be processed and rendered, and in a failed callback, I directly get the wrong code. Is it possible to package it in one step?

In fact, these two questions are one. To sum up one sentence, I don't want to write so many if and else. There is a sentence that I think is very good. Logic is conservative, but if it is predictable logic, it is possible to simplify it. Our logic obviously belongs to predictable logic.

The second encapsulation uses the then method of delayed objects. See the code for details:


function handleAjax(url, param, type) {
return ajax(url, param, type).then(function(resp){
//  Successful callback 
if(resp.result){
return resp.data; //  Returns the data to be processed directly, and after passing in as the default parameter, done() Method callback 
}
else{
return $.Deferred().reject(resp.msg); //  Return 1 Of the failed state deferred Object, passing the error code as the default parameter fail() Method callback 
}
}, function(err){
//  Failed callback 
console.log(err.status); //  Print status code 
});
}
handleAjax('www.baidu.com/getInfo').done(function(resp){
//  When result For true Callback of 
}).fail(function(err){
//  When result For false Callback of 
});

This simplifies the code that was very miscellaneous before, and it is also convenient for maintenance. For example, I told you one day that result is no longer a Boolean value, and it is directly changed to something like status code. If you write a judgment according to the previous ajax, it will be crazy.


Related articles: