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