Customize your favorite API based on jQuery Ajax

Time:2019-12-10

Customize your favorite API based on jQuery Ajax

What do you think of jQuery’s Ajax API? Do you want to customize the silky API more suitable for you.

This article is based on my previous article “http.js application in Ajax single page”.


You can scan the two-dimensional code at the end of the article and pay close attention to my public address. Most of the contents will be back-end technology, front-end engineering, DevOps, and occasionally there will be some big data related, which will recommend some interesting things. I hope you like it~


It’s not easy to write regular Ajax code, because different browsers implement Ajax differently. However, jQuery has helped to deal with these compatibles, but I still feel uncomfortable when I write too much code, because it can’t give me the following experience:

  1. Simpler chain API;

  2. All requests in the page need to attach some common parameters;

  3. The user-defined errors returned by the service cannot be handled uniformly;

New API

Programmers who don’t like to do things are not good siegers. ? so, based on jQuery, I repackaged a layer.

This is an example

//Additional common parameters
$http.global("token","abcd321"); 
$http.use("/api",  (res) =>  {
    if (res.success) {
        return true;
    }
    var err = res.error;
    if (err.code === 1001) {
        location.href = "/login.html";
    } else {
        alert(err.message);
    }
    return false;
});

$http.get("/api/user").type("json")
.param("id", 110) .send( (res) =>  { 
       //This step will not be performed until the filter is processed
       var datum = res.datum;
       alert("Name: " + datum.name);
       console.log(res.datum);
    }, (err) => {
       Alert ("query failed amount");
       console.error(err);
     });

This is the detailed API description

Set common parameters;

  • $http.global(key, value);

Set the filter;

  • $http.use(urlPrefix, option [optinal], callback);

Set request type;

  • $http.get(url);

  • $http.getJson(url);

  • $http.post(url);

  • $http.put(url);

  • $http.delete(url);

Add request parameters;

  • $http.param(key, value);

  • $http.params(paramJson);

Set request header;

  • $http.header(key, value);

  • $http.headers(paramJson);

Other extension options;

  • $http.cache(boolean);

  • $http.type("json/xml/html");

  • $http.async(boolean);

  • $http.timeout(number);

Send request and process callback;

  • $http.send(options [optional], successCallback, errorCallback);

Gist address

https://gist.github.com/lenbo-ma/0213bfe…


Long press QR code and follow me.

Most of the content will be back-end technology, front-end engineering, Devops, occasionally there will be some big data related, and some interesting things will be recommended. I hope you like it~

Customize your favorite API based on jQuery Ajax

Everything comes from liking.