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

posted @ 2019-01-23 11:55  素衣居士  阅读(3968)  评论(0编辑  收藏  举报