<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                [TOC] ## 簡單例子 ``` var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ // 通信成功時,狀態值為4 if (xhr.readyState === 4){ if (xhr.status === 200){ console.log(xhr.responseText); } else { console.error(xhr.statusText); } } }; xhr.onerror = function (e) { console.error(xhr.statusText); }; xhr.open('GET', '/endpoint', true); xhr.send(null); ``` ## 屬性 ### readyState * 0,實例已經生成,`open()`方法沒被調用 * 1,`open()`方法已經調用,`send()`方法沒有調用,仍可使用實例的`setRequestHeader()`方法,設定 HTTP 請求的頭信息。 * 2,`send()`方法已經調用,并且服務器返回的頭信息和狀態碼已經收到。 * 3,接收服務器的數據體(body)。這時,如果實例的`responseType`屬性等于`text`或者空字符串,`responseText`屬性就會包含已經收到的部分信息。 * 4,表示服務器返回的數據已經完全接收,或者本次接收已經失敗。 ### onreadystatechange 添加 `readyState` 的變化 ### response 服務器返回的數據體 可以是任何數據類型,字符串、對象、二進制對象 ### responseType 返回的數據類型 * ""(空字符串):等同于`text`,表示服務器返回文本數據。 * "arraybuffer":ArrayBuffer 對象,表示服務器返回二進制數組。 * "blob":Blob 對象,表示服務器返回二進制對象。 * "document":Document 對象,表示服務器返回一個文檔對象。 * "json":JSON 對象。 * "text":字符串。 如果設置返回值為 `json` 則`xhr.response` 返回json對象 不能通過 `responseText` 取得對象 ``` var xhr = new XMLHttpRequest(); xhr.open('get', 'test.php', true); xhr.responseType='json'; //設置發回值類型 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log(xhr.response.name); } else { console.error(xhr.status); } } } xhr.onerror = function () { console.log(xhr.statusText); } xhr.send(null) ``` ### responseText 從服務器接收到的字符串 如果沒有指定返回類型,默認使用此方法 ### responseXML 返回執行后的DOM 文件 1. `Content-Type`是`text/html`和`application/xml`,只需設置 `responseType`屬性為`document` 2. 如果 HTTP 回應的`Content-Type`頭信息不等于`text/xml`和`application/xml`,還需設置`overrideMimeType('xml')` ``` xhr.responseType = 'document'; //若Content-type 不是 text/xml 或者 application/xml xhr.overrideMimeType('text/xml'); ``` ### responseURL 請求的地址 ### status / statusText 返回狀態嗎和描述 ### timeout / ontimeout 是指超時時間 超時觸發的函數 ``` var xhr = new XMLHttpRequest(); xhr.open('GET', '/server); xhr.ontimeout = function () { console.error('The request for ' + url + ' timed out.'); }; xhr.timeout = 10 * 1000; // 指定 10 秒鐘超時 xhr.send(null); ``` ### withCredentials 跨域請求時,是否包含用戶信息(如Cookie 和認證的 HTTP 頭信息) 默認為`false` ``` var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', true); xhr.withCredentials = true; xhr.send(null); ``` ### upload 異步文件上傳 `<progress min="0" max="100" value="0">0% complete</progress> ` ``` function upload(blobOrFile) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/server', true); xhr.onload = function (e) {}; var progressBar = document.querySelector('progress'); xhr.upload.onprogress = function (e) { if (e.lengthComputable) { progressBar.value = (e.loaded / e.total) * 100; // 兼容不支持 <progress> 元素的老式瀏覽器 progressBar.textContent = progressBar.value; } }; xhr.send(blobOrFile); } upload(new Blob(['hello world'], {type: 'text/plain'})); ``` ## 事件監聽屬性 ``` XMLHttpRequest.onloadstart:loadstart 事件(HTTP 請求發出)的監聽函數 XMLHttpRequest.onprogress:progress事件(正在發送和加載數據)的監聽函數 XMLHttpRequest.onabort:abort 事件(請求中止,比如用戶調用了abort()方法)的監聽函數 XMLHttpRequest.onerror:error 事件(請求失敗)的監聽函數 XMLHttpRequest.onload:load 事件(請求成功完成)的監聽函數 XMLHttpRequest.ontimeout:timeout 事件(用戶指定的時限超過了,請求還未完成)的監聽函數 XMLHttpRequest.onloadend:loadend 事件(請求完成,不管成功或失敗)的監聽函數 ``` demo: ``` xhr.onload = function() { var responseText = xhr.responseText; console.log(responseText); // process the response. }; xhr.onabort = function () { console.log('The request was aborted'); }; xhr.onprogress = function (event) { console.log(event.loaded); console.log(event.total); }; xhr.onerror = function() { console.log('There was an error!'); }; ``` ## 實例方法 ### open() 初始化請求實例 ``` void open( string method, string url, optional boolean async, optional string user, optional string password ); ``` ### send() 實例發出http 發送的數據格式 其他參數類型 ``` void send(); void send(ArrayBufferView data); void send(Blob data); void send(Document data); void send(String data); void send(FormData data); ``` 如果為post ``` var xhr = new XMLHttpRequest(); var data = 'email=' + encodeURIComponent(email) + '&password=' + encodeURIComponent(password); xhr.open('POST', 'http://www.example.com', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(data); ``` 發送表單 ``` var formData = new FormData(); formData.append('username', '張三'); formData.append('email', 'zhangsan@example.com'); formData.append('birthDate', 1940); var xhr = new XMLHttpRequest(); xhr.open('POST', '/register'); xhr.send(formData); ``` ### setRequestHeader 設置請求頭 ``` xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Content-Length', JSON.stringify(data).length); xhr.send(JSON.stringify(data)); ``` ### overrideMimeType 覆蓋原MIME的值 服務器返回的數據類型是`text/xml`,由于某種原因,解析不成功,為了拿到原始數據,我們可以把 MIME 類型改成`text/plain`,這樣瀏覽器就不會解析,就可拿到原始數據 `xhr.overrideMimeType('text/plain') ### getResponseHeader 返回頭字段信息 ``` var xhr = new XMLHttpRequest(); xhr.open('get','/test.php') xhr.onload=function (e) { console.log(this.getResponseHeader('Date')); } xhr.send(); ``` ### getResponseHeader() 返回所有都字段信息 ### abort() 禁止放請求 調用這個方法以后,`readyState`屬性變為`4`,`status`屬性變為`0` ``` var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.example.com/page.php', true); setTimeout(function () { if (xhr) { xhr.abort(); xhr = null; } }, 5000); ``` ## XMLHttpRequest 可監聽事件 ### readyStateChange 事件 此事件使用 `onreadyStateChange` 監聽 ``` xhr.onreadystatechange=function () { console.log(xhr.readyState); } ``` ### progress 事件 ``` var xhr = new XMLHttpRequest(); function updateProgress (oEvent) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total; } else { console.log('無法計算進展'); } } xhr.addEventListener('progress', updateProgress); xhr.open(); ``` ### load 事件、error 事件、abort 事件 ``` var xhr = new XMLHttpRequest(); xhr.addEventListener('load', transferComplete); xhr.addEventListener('error', transferFailed); xhr.addEventListener('abort', transferCanceled); xhr.open(); function transferComplete() { console.log('數據接收完畢'); } function transferFailed() { console.log('數據接收出錯'); } function transferCanceled() { console.log('用戶取消接收'); } ``` #### loadend 事件 `abort`、`load`和`error`這三個事件,會伴隨一個`loadend`事件,表示請求結束,但不知道其是否成功。 ``` xhr.addEventListener('loadend', loadEnd); function loadEnd(e) { console.log('請求結束,狀態未知'); } ``` ### timeout 事件 ``` xhr.addEventListener('timeout',function () { console.log('timeout'); }) xhr.timeout=100 ``` ### Navigator.sendBeacon() 卸載頁面是發送數據 由于 `XMLHttpRequest` 不能保證發出清楚,使用這個方法 ``` window.addEventListener('unload', logData, false); function logData() { navigator.sendBeacon('/log', analyticsData); } ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看