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);
            }
        }
    }
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM