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浏览器兼容

o_fetchw.png
t_fetchw.png
本文摘抄于
XMLHttpRequest

Fetch

转载于:https://www.cnblogs.com/wentutu/p/10308103.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值