JavaScript:fetch,实现异步请求

JavaScript:fetch(),实现异步请求

fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。

fetch

  • 参数

    1. URL:请求地址
    2. option:配置选项,用了设置方法、请求头、请求body等;
  • 示范

    fetch(URL,{
          
          
        method : 'POST',
        body : data,
        headers : {
          
          
            "ContentType" : "application/json"
        }
        // 其他配置
    })
        .then(response=>response.json())	//返回一个promise对象
        .then(data=>console.log(data))
        .catch(error=>console.log(error))
    
  • 进阶版

  • 也可以new 一个 Request对象,配置好后再传入fetch方法

    let req = new Request(URL,{
          
          method : 'POST'});
    fetch(req)
        .then(response=>response.json())
    	.then(data=>console.log(data));	
    

猜你喜欢

转载自blog.csdn.net/yivisir/article/details/108000805