ajax

  • Ajax — XMLHttpRequest() 對(duì)象

優(yōu)點(diǎn):無需重新加載整個(gè)網(wǎng)頁的情況下,實(shí)現(xiàn)部分網(wǎng)頁更新的技術(shù)。提高用戶體驗(yàn),Ajax技術(shù)的核心是XMLHttpRequest對(duì)象(簡稱XHR);像ajax這種耗時(shí)長的操作應(yīng)該異步執(zhí)行,避免瀏覽器失去響應(yīng)。

缺點(diǎn):1、不支持瀏覽器back按鈕;2、安全問題,暴露與服務(wù)器的交互細(xì)節(jié);3、對(duì)搜索引擎的支持較弱;4、不容易調(diào)試;5、破壞了程序異常機(jī)制

ajax流程:

  1. 創(chuàng)建XMLHttpRequest對(duì)象 var xhr = new XMLHttpRequest();
  2. 創(chuàng)建新的http請(qǐng)求,指定請(qǐng)求方法、url、驗(yàn)證信息等。xhr.open('get', 'url', true/false[是否異步]) [true表示會(huì)在send后繼續(xù)執(zhí)行,而不等待服務(wù)器的響應(yīng)]
    • 若是post請(qǐng)求,需要設(shè)置請(qǐng)求頭格式的內(nèi)容:xhr.setRequestHeader('content-type', 'application/x-www-form-urlenCoded'); [表單提交的格式]
  3. 設(shè)置響應(yīng)http請(qǐng)求狀態(tài)變化的函數(shù)。
    xhr.onreadyStatechange = function () {
    if(xhr.readyState == 4 && xhr.status == 200) {
    // 處理:xhr.responseText / responseXML
    }
    }
  4. 發(fā)送http請(qǐng)求 :xhr.send(),[若是POST請(qǐng)求,需要寫傳入的string] — "methodName = GetAllComment&str1=str1&str2=str2"
  5. 獲取返回的數(shù)據(jù)并做后續(xù)處理,一般接收異步返回的數(shù)據(jù),axios等操作
  6. 異常捕獲:axios catch ,原生:try { xhr.send();} catch (e) { console.log(e);}

readyState:0:請(qǐng)求初始化;1:服務(wù)器連接已確立;2:請(qǐng)求已接收;3:請(qǐng)求處理中;4:請(qǐng)求完成,響應(yīng)就緒

abort()`:取消異步HTTP請(qǐng)求

getAllResponseHeaders()`: 返回一個(gè)字符串,包含響應(yīng)中服務(wù)器發(fā)送的全部HTTP報(bào)頭。每個(gè)報(bào)頭都是一個(gè)用冒號(hào)分隔開的名/值對(duì),并且使用一個(gè)回車/換行來分隔報(bào)頭行

getResponseHeader(headerName)`:返回headName對(duì)應(yīng)的報(bào)頭值

  • 原生Ajax請(qǐng)求過程

手撕過程

function getXHR(){
  var xhr = null;
  if(window.XMLHttpRequest) {// 兼容 IE7+, Firefox, Chrome, Opera, Safari
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");// 即MSXML3
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");// // 兼容 IE6, IE5,很老的api,雖然瀏覽器支持,功能可能不完善,故不建議使用
      } catch (e) {
        alert("您的瀏覽器暫不支持Ajax!");
      }
    }
  }
  return xhr;
}

var xhr = getXHR();
xhr.open('GET', url/file,true);  //設(shè)置請(qǐng)求方式,url,以及是否異步
xhr.onreadystatechange = function() {   //設(shè)置回調(diào)監(jiān)聽函數(shù)
   if(xhr.readyState==4){
        if(xhr.status==200){
            var data=xhr.responseText;
             console.log(data);
   }
};
xhr.onerror = function() {
  console.log("Oh, error");
};
xhr.send();  //發(fā)送請(qǐng)求

封裝為插件

GET

function getJSON (url) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.responseText, this)
                } else {
                    var resJson = { code: this.status, response: this.response }
                    reject(resJson, this)
                }
            }
        }
        xhr.send()
    })
}

post

function postJSON(url, data) {
    return new Promise( (resolve, reject) => {
        var xhr = new XMLHttpRequest()
        xhr.open("POST", url, true)
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(JSON.parse(this.responseText), this)
                } else {
                    var resJson = { code: this.status, response: this.response }
                    reject(resJson, this)
                }
            }
        }
        xhr.send(JSON.stringify(data))
    })
}

使用

getJSON('/api/v1/xxx')    // => 這里面是就try
.catch( error => {
  // dosomething          // => 這里就是catch到了error,如果處理error以及返還合適的值
})
.then( value => {
  // dosomething          // 這里就是final
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • ??2005 年,Jesse James Garrett 發(fā)表了一篇在線文章,題為“Ajax: A new App...
    霜天曉閱讀 902評(píng)論 0 1
  • 1、XMLHttpRequest 對(duì)象 在瀏覽器中創(chuàng)建XHR 對(duì)象 1.1 XHR 的用法 在使用XHR 對(duì)象時(shí),...
    shanruopeng閱讀 594評(píng)論 0 1
  • Ajax:Asynchronous JavaScript + XML的簡寫。Ajax技術(shù)的核心是XMLHttpRe...
    exialym閱讀 889評(píng)論 0 8
  • AJAX 原生js操作ajax 1.創(chuàng)建XMLHttpRequest對(duì)象 var xhr = new XMLHtt...
    碧玉含香閱讀 3,274評(píng)論 0 7
  • 看完了《驢得水》,總體感覺是好精致。雖然演員不是特別有名,但是的確有舞臺(tái)劇那種緊張氛圍,幾經(jīng)轉(zhuǎn)折,人性大變。整個(gè)電...
    我不是注銷了嗎閱讀 229評(píng)論 0 0