自已封装Ajax方法

function createXHR() {
    var request;
    if (typeof (XMLHttpRequest) == 'undefined') {
        request = new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        request = new XMLHttpRequest();
    }
    return request;
}

var xhr = createXHR();

function ajax(method, url, isAsync, data, fnsuccess, fnerror) {
    xhr.open(method, url, isAsync);
    if (method.toLocaleLowerCase() == 'post') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                return fnsuccess(xhr.responseText);
            } else {
                return fnerror();
            }
        }
    };
    xhr.send(data);
}

function get(url, fnsuccess) {
    return ajax("get", url, true, null, fnsuccess, null);
}

function post(url, data, fnsuccess) {
    return ajax("post", url, true, data, fnsuccess, null);
}

 

posted on 2014-06-13 15:18  非零  阅读(238)  评论(0编辑  收藏  举报