Jq ajax encapsulation and jqajax Encapsulation
In the current era of plug-ins, when react, vue, and angularjs are popular today, I still use jq ajax to connect data, and I always feel that I cannot keep up with the pace of the times. Recently, I am slowly learning react and vue, but these old things are still saved. After all, it is my own growth process.
(Assume the address is http: // haha/get/user)
Function demoAjax (opt ){
Var isdefult = opt. isdefult | "need"; // determines whether this function is required to determine whether the data returned from the page request is returned.
$. Ajax ({
Url: 'http: // haha/'+ opt. url, // path of the data interface
DataType: 'json ',
Type: opt. type | "get", // The default request method is get.
Data: opt. param | "", // The request parameter is blank by default.
Async: opt. async | true, // whether it is asynchronous. The default value is asynchronous.
Timeout: 10000,
Success: function (res ){
/* Opt. isLoading = undefined & app. loading ('hide '); * // determine whether to load the function. My loading function is encapsulated in an object and executed based on your own project to determine whether to load the animation.
If (isdefult = "need") {// determine whether this function is required or not after the data returned by the page request is returned.
If (res. code = 0) {// judge based on the return result of your project
Opt. successBack instanceof Function & opt. successBack (res. data); // The success Function, depending on the value of your project
}
Else {
Console. log (res. msg)
}
}
Else
{
Opt. successBack instanceof Function & opt. successBack (res );
}
},
Error: function (xhr, type, errorThrown ){
Console. log (JSON. stringify (xhr ));
Console. log (type );
Console. log (errorThrown );
}
});
}
See what you like. You can choose to extend to jquery or a function.
Usage:
Simple get request: (assume the address is http: // hahahha/get/user)
DemoAjax ({
"Url": "get/user ",
"Succsponack": funtion () {// processing after successful}
})
Post request:
DemoAjax ({
"Url": "get/user ",
"Type": "post ",
"Param": {"user": "xg "}
"Succsponack": funtion () {// processing after successful}
})
Others are adapted based on the project.