当前位置 : 主页 > 编程语言 > c++ >

JavaScript Native XHR

来源:互联网 收集:自由互联 发布时间:2021-07-03
Use of native ajax api /** * Use of native ajax api */// simple ajax with timeoutfunction simpleAjax(method, url, data, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { // try-ca
Use of native ajax api
/**
 * Use of native ajax api
 */

// simple ajax with timeout
function simpleAjax(method, url, data, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            // try-catch is necessary when you use timeout
            try {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                    callback(xhr.responseText);
                }
            } catch (e) {}
        }
    };

    xhr.open(method, url, true);
    xhr.ontimeout = function () {
        // do something here
    };
    // if method is get, you should set data null
    xhr.send(data);
}

// encapsulation of get method
function get(url, headers, params, callback) {
    header = header ||  {};
    params = params || {};
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                callback(xhr.responseText);
            }
        }
    };

    var queryList = [];
    for (var p in params) {
        if (params.hasOwnProperty(p)) {
            queryList.push(p + '=' + params[p]);
        }
    }
    var query = queryList.length ? '?' + queryList.join('&') : '';
    xhr.open('get', url + query, true);
    for (var h in headers) {
        if (headers.hasOwnProperty(h)) {
            xhr.setRequestHeader(h, headers[h]);
        }
    }
    xhr.send(null);
}

// encapsulation of post method
function post(url, headers, params, callback) {
    header = header ||  {};
    params = params || {};
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                callback(xhr.responseText);
            }
        }
    };

    xhr.open('post', url, true);
    for (var h in headers) {
        if (headers.hasOwnProperty(h)) {
            xhr.setRequestHeader(h, headers[h]);
        }
    }
    var data = new FormData();
    for (var p in params) {
        if (params.hasOwnProperty(p)) {
            data.append(p, params[p]);
        }
    }
    xhr.send(data);

    // var form = document.getElementById('user-info');
    // xhr.send(new FormData(form));
}

/**
 * load event
 * process-flow:
 *          loadStart ->
 *          progress(one or more)
 *          -> [error | abort | load](one of them)
 *          -> loaded
 */

function loadProgress(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
            callback(xhr.responseText);
        }
    };

    xhr.onprogress = function (evt) {
        if (evt.lengthComputable) {
            console.log(evt.position / evt.totalSize + ' %');
        }
    };
    xhr.open('get', url, true);
    xhr.send(null);
}
网友评论