js 發送異步請求


js用XMLHttpRequest發送異步請求

發送GET請求


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請求


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

獲取頭信息:


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數據


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

Fetch


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM