js 發送異步請求

js用XMLHttpRequest發送異步請求

發送GET請求html

var xhr = new XMLHttpRequest();
xhr.open('GET',url);//url爲請求地址
xhr.responseType = 'json';
xhr.onload = function () {
   // 請求結束後,在此處寫處理代碼
};
xhr.onerror = function(){//請求錯誤
    console.log('xhr error');
}

xhr.send();

發送POST請求json

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//發送合適的請求頭信息
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // 請求結束後,在此處寫處理代碼
    }
}
xhr.send("foo=bar&lorem=ipsum");

Fetch發送請求 除了IE和Safari瀏覽器不支持,別的瀏覽器大多提供了支持。(如今Safari也即將爲fetch和promise提供支持)

//fetch()返回一個promise,它將解析從服務器發回的響應。咱們使用then()來運行一些後續代碼
fetch(url).then(function(response){
    //處理text/html響應 至關於  xhr.responseType = 'json';
    //return response.text(); 
    //json響應
    return response.json();
}).then(function(data){ //至關於xhr.onload =function(){}
    console.log(data);
}).catch(function(e){//至關於xhr.onerror =function(){}
    console.log('error' + e);
});

獲取頭信息:promise

fetch(url).then((response)=>{
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers.get('Content-Type'));
    console.log(response.headers.get('Date'));
    return response.json();
}).then(function(data){ 
    console.log(data);
})
  .catch(function(e){
    console.log('error' + e);
});

設置頭信息瀏覽器

fetch(url,{
    headers:{
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
}).then((response)=>{
    return response.json();
}).then(function(data){ 
    console.log(data);
})
  .catch(function(e){
    console.log('error' + e);
});

提交表單服務器

fetch(url,{
    method: 'post',
    body: new FormData(document.getElementById('form'))
}).then((response)=>{
    return response.json();
}).then(function(data){ 
    console.log(data);
})
  .catch(function(e){
    console.log('error' + e);
});

提交json數據app

fetch(url,{
    method: 'post',
    body: JSON.stringify({
        username: document.getElementById('username').value,
        password: document.getElementById('password').value
    })
}).then(function(data){ 
    console.log(data);
})
  .catch(function(e){
    console.log('error' + e);
});

Fetch瀏覽器兼容



本文摘抄於
XMLHttpRequest異步

Fetchpost

相關文章
相關標籤/搜索