jquery-based Ajax method encapsulation _jquery

Source: Internet
Author: User
Tags error code mixed

Introduction to Ajax (Ajax development)

Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), refers to a web development technology that creates interactive Web applications.

AJAX = Asynchronous JavaScript and XML (a subset of standard generic markup languages).

AJAX is a technique for creating fast-moving web pages.

AJAX enables asynchronous updating of Web pages by making a small amount of data exchange in the background with the server. This means you can update portions of a Web page without reloading the entire page.

In the actual project, AJAX application frequency is very high, so although jquery or some other similar JS library to do a very good package, there are still further encapsulation of the space and the need for 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's fine, but in fact the logic in the success callback may be complicated, and there may even be an AJAX callback in the AJAX context, and it's a bad one, all mixed up.

A simple encapsulation can be made, which has already been mentioned in the deferred object's essay

function ajax (URL, param, type) {
////Using jquery deferred object callback for Ajax encapsulation, using done (), fail (), always (), and other methods for chained callback operations
/ If you need more parameters, such as a Cross-domain datatype need to be set to ' Jsonp ' and so on, you can consider the parameter set to the object return
$.ajax ({
url:url,
data:param | | {},
Type:type | | ' Get '
});
Chained callback
Ajax (' Www.baidu.com/getInfo '). Done (function (RESP) {
//successful callback
}). Fail (function (ERR) {
/ Failed callback
});

But although this step, the problem will come, such as Division I, the success of the callback there is a layer of logic, like this:

Our AJAX returned JSON data format
//When result is false, MSG often has error message
{
result:true,
data: {
name: ' Jack '
},
msg:null
}
Ajax (' Www.baidu.com/getInfo '). Done (function (RESP) {
//successful callback
if ( Resp.result) {
///When result is true in RESP
//often this time to manipulate the data object information in Resp
}
else{
// When result is false, the specific processing} is often judged according to another attribute msg in RESP
. Fail (function (ERR) {
//failed callback
});

There are two questions:

First, I need to write the same relatively fixed logic in each AJAX (each company or project team may be different, but in terms of the project itself, or zoom in to the company must be fixed), I find it annoying.

Second, if I just want to focus on data, like in a successful callback, I get directly to the data to be rendered, I get the wrong code directly in the failed callback, and there is no possibility of further encapsulation.

In fact, these two problems is one, summed up a word, is not want to write so many if,else. There is a saying that I think is very good, the logic is conserved, but if it is predictable logic, there is the possibility of streamlining, we clearly belong to the foreseeable logic.

The two-time encapsulation utilizes the then method of the deferred object, looking at the code specifically:

function handleajax (URL, param, type) {return
ajax (URL, param, type). Then (function (RESP) {
//Success Callback
if ( Resp.result) {
return resp.data;//Returns the data to be processed directly, as a callback to the done () method after the default parameter is passed in ()
else{back
$. Deferred (). Reject (RESP.MSG); Returns a deferred object with a failed state that passes the error code as the default parameter to the Fail () method's callback
}
}, function (err) {
//failed callback
Console.log ( Err.status); Print status Code
});
Handleajax (' Www.baidu.com/getInfo '). Done (function (RESP) {
//callback with result true)
. Fail (function (ERR) {
//When result is False (callback
});

This is the previous very mixed code further simplification, but also convenient maintenance, such as one day with you say that result is no longer a Boolean value, directly changed to the status code such things, if the previous one to write an AJAX judgment, it is crazy.

The above is a small series of the introduction of jquery based on the Ajax method of encapsulation, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.