Ajax method of jquery

background

Refer to the ajax api of jquery to encapsulate an ajax method

Technical Difficulties

  • jsonp package
  • promise support
  • formData support
  • Convenience method encapsulation
  • Modular support

jsonp package

The principle of jsonp is based on the script tag, assigning a request interface to src, passing a callback function (?callback=jsonp12121)to the server, and the server typeof jsonp12121 === 'function' && jsonp12121(respData)responding to the browser in the form of a response.

Complete jsonp package

function JSONP(options) {
    //
    var callbackName = options.jsonpCallback || 'jsonp' + (new Date().getTime());

    var script = window.document.createElement('script');

    var abort = function () {
        // 设置 window.xxx = noop
        if (callbackName in window) {
            window[callbackName] = noop;
        }
    };

    var xhr = {abort: abort};
    var abortTimeout;

    var head = window.document.getElementsByTagName('head')[0] || window.document.documentElement;

    // ie8+
    script.onerror = function (error) {
        _error(error);
    };

    function _error(error) {
        window.clearTimeout(abortTimeout);
        xhr.abort();
        ajaxError(error.type, xhr, error.type, options);
        _removeScript();
    }

    window[callbackName] = function (data) {
        window.clearTimeout(abortTimeout);
        ajaxSuccess(data, xhr, options);
        _removeScript();
    };

    //
    serializeData(options);

    script.src = options.url.replace(/=\?/, '=' + callbackName);
    //
    script.src = appendQuery(script.src, '_=' + (new Date()).getTime());
    //
    script.async = true;

    // script charset
    if (options.scriptCharset) {
        script.charset = options.scriptCharset;
    }

    //
    head.insertBefore(script, head.firstChild);

    //
    if (options.timeout > 0) {
        abortTimeout = window.setTimeout(function () {
            xhr.abort();
            ajaxError('timeout', xhr, 'timeout', options);
            _removeScript();
        }, options.timeout);
    }

    // remove script
    function _removeScript() {
        if (script.clearAttributes) {
            script.clearAttributes();
        } else {
            script.onload = script.onreadystatechange = script.onerror = null;
        }

        if (script.parentNode) {
            script.parentNode.removeChild(script);
        }
        //
        script = null;

        delete window[callbackName];
    }

    return options.promise;
}

promise support

By setting the returned object to be a Promise object, promise support can be achieved.

ie8 is not supported.

let ajax = function(options){
    var settings = extend({}, options || {});
    <!--promise 支持--> 
    try {
        var q = {};
        var promise = new Promise(function (resolve, reject) {
            q.resolve = resolve;
            q.reject = reject;
        });

        promise.resolve = q.resolve;
        promise.reject = q.reject;

        settings.promise = promise;
    } catch (e) {
        //
        settings.promise = {
            resolve: noop,
            reject: noop
        };
    }
    
    
    <!---->
    return settings.promise;
}

formdata support

Only need to set processDatato falseand is set contentTypetofalse

let formData = new FormData();
ajax({
    url: '/upload',
    type: 'POST',
    cache: false,
    data: formData,
    processData: false,
    contentType: false
})

Convenience method encapsulation

  • ajax.get()

  • ajax.post()

  • ajax.getJSON ()

  • ajax.ajaxSetup ()

Modular support

 // RequireJS && SeaJS
if (typeof define === 'function') {
    define(function () {
        return ajax;
    });
    // NodeJS
} else if (typeof exports !== 'undefined') {
    module.exports = ajax;
} else {
    // browser
    window.ajax = ajax;
}

Supported parameters

url

(A string containing the URL used to send the request.)

accepts

(Default: Depends on the data type.) The
content type sends the request header, telling the server what kind of response will be returned. If the accepts setting needs to be modified, it is recommended to do it once in the ajaxSetup() method.

async

(Default: true) By default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the
synchronization request will lock the browser, and other user operations must wait for the completion of the request before they can be executed. )

beforeSend(XHR)

(You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.
This is an Ajax event. If you return false, you can cancel the ajax request.)

function (XMLHttpRequest) {
    this; // 调用本次AJAX请求时传递的options参数
}

complete(XHR, TS)

Callback function after the request is completed (call both after the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request.

function (XMLHttpRequest, textStatus) {
    this; // 调用本次AJAX请求时传递的options参数
}

contentType

(Default: "application/x-www-form-urlencoded") The content encoding type when sending information to the server. The default value is suitable for most situations.
If you explicitly pass a content-type to ajax() then it must be sent to the server (even if there is no data to send)

context

(This object is used to set the context of Ajax-related callbacks. In other words, let the callback function this point within the object (if you do not set this parameter,
then this points to the options parameter passed when calling this AJAX request).
For example, Specify a DOM element as the context parameter, so that the context of the success callback function is set to this DOM element. Like this:)

$.ajax({ url: "test.html", context: document.body, success: function(){
    $(this).addClass("done");
}});

crossDomain

(Default: Same domain request is false)
Cross domain request is true If you want to force cross domain request (such as JSONP format) to the same domain, set crossDomain to true. This makes for example, server-side redirection to another domain

data

(The data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. Check the processData option description to prohibit this automatic conversion. It
must be in Key/Value format. If it is an array, jQuery will automatically Different values ​​correspond to the same name. For example, {foo:["bar1", "bar2"]} is converted to "&foo=bar1&foo=bar2".)

dataType

The type of data that the server is expected to return. If not specified, it will be automatically judged intelligently based on the MIME information of the HTTP package. For example, the XML MIME type is recognized as XML. In 1.4, JSON will generate a JavaScript object, and script will execute the script.
Then the data returned by the server will be parsed according to this value and passed to the callback function. Available values:

"Xml": Return an XML document, which can be processed by jQuery.

"Html": Returns the plain text HTML information; the included script tag will be executed when the dom is inserted.

"Json": Return JSON data.

"Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl?callback=?" jQuery will automatically replace? With the correct function name to execute the callback function.

"Text": return a plain text string

"*": Any type

error(XMLHttpRequest, textStatus, errorThrown)

(Default: automatic judgment (xml or html)) This function is called when the request fails. There are three parameters: XMLHttpRequest object, error message, and (optional) the captured exception object. If an error occurs, the error message (the second parameter)
may be "timeout", "error", "notmodified" and "parsererror" in addition to null.

function (XMLHttpRequest, textStatus, errorThrown) {
    // 通常 textStatus 和 errorThrown 之中
    // 只有一个会包含信息
    this; // 调用本次AJAX请求时传递的options参数
}

headers

An additional "{key:value}" pair is mapped to the request and sent together. The beforeSend function is called before this setting is set; therefore, the value setting in the message header can override any setting within the scope of the beforeSend function.

jsonp

Rewrite the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in the "callback=?" GET or POST request. For
example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

jsonpCallback

Specify a callback function name for the jsonp request. This value will be used to replace the random function name automatically generated by jQuery. This is mainly used to allow jQuery to generate unique function names,
so that it is easier to manage requests, and it is also convenient to provide callback functions and error handling. You can also specify the callback function name when you want the browser to cache GET requests.

success(data, textStatus, jqXHR)

The callback function after the request is successful. Parameters: The data returned by the server and processed according to the dataType parameter; a string describing the status.

function (data, textStatus) {
    // data 可能是 xmlDoc, jsonObj, html, text, 等等...
    this; // 调用本次AJAX请求时传递的options参数
}

timeout

Set the request timeout time (in milliseconds). This setting will override the global setting.

type

(Default: "GET") Request method ("POST" or "GET"), the default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but only some browsers support.

username

User name used to respond to HTTP access authentication requests

password

Password used to respond to HTTP access authentication requests

processData

(Default: true) By default, the data passed in through the data option, if it is an object (technically speaking, as long as it is not a string), it
will be processed and converted into a query string to match the default content type "application/x- www-form-urlencoded".
If you want to send DOM tree information or other information that you don't want to convert, please set it to false.

xhrFields

Object object. Can support withCredentials, Access-Control-Allow-Credentials, the parameters of
which withCredentials compatibility is IE10+

mimeType

(A mime type is used to override the MIME type of XHR.)

ifModified

((Default: false) Only get new data when the server data is changed. Use the HTTP packet Last-Modified header to determine. The
server specified'etag' will also be checked to make sure that the data has not been modified.)

cache

((Default: true, the default is false when dataType is script and jsonp) If set to false, this page will not be cached.)

Parameters not currently supported

xhr

(Use the default xhr (XMLHttpRequest, compatible with ie8+)

traditional

(If you want to serialize the data in the traditional way, set it to true.)

statusCode

(A set of numeric HTTP codes and function objects, and the corresponding codes are called when responding. For example, if the response status is 404, the following alarm will be triggered:)

ajax({
  statusCode: {404: function() {
    alert('page not found');
  }
});

isLocal

(Default: Depends on the current location protocol)
(Allows the current environment to be recognized as "local" (such as the file system), even if jQuery does not recognize it by default. The
following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal settings need to be modified, it is recommended to do this once in the $.ajaxSetup() method.)

global

(Default: true) Whether to trigger global AJAX events. Setting to false will not trigger global AJAX events, such as ajaxStart or ajaxStop can be used to control different Ajax events.

dataFilter

(A function to preprocess the original data returned by Ajax. Provide two parameters: data and type: data is the original data returned by Ajax, and
type is the dataType parameter provided when calling Ajax. The value returned by the function will be further processed by jQuery.)

converters

(Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML})
(a data type to data type converter object .The value of each converter is a function that returns the converted value of the response)

contents

An object paired with "{string:regular expression}" is used to determine how the response will be parsed, given its content type.

github

https://github.com/bosscheng/simple-ajax

Guess you like

Origin blog.csdn.net/wancheng815926/article/details/106032027