js 封装自己的Ajax函数

封装自己的Ajax函数

主要是兼容自己的get,post两种不同请求的请求方式,在实现一下兼容的处理

 ajax.open(method,url,true) 方法post get 请求地址 异步true 同步false
 ajax.send() 发送
 onreadystatechange 监听数据 返回4 数据已经请求回来了
 
代码实现:
function ajaxFn(method, url, callBack,data,flag) {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHttp')
    }
    method = method.toUpperCase();
    if (method == 'GET') {
        xhr.open(method, url+'?'+data, flag);
        xhr.send();
    } else if (method == 'POST') {
        xhr.open(method, url, flag);
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
        xhr.send(data);
    }
   
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                //    xhr.responseText   //返回回来的值
                callBack(xhr.responseText);
            }
        }
    }
}

  

posted @ 2019-07-12 09:18  chris_z_y  阅读(2511)  评论(0编辑  收藏  举报