美文网首页
fetch API的基本使用方法

fetch API的基本使用方法

作者: 小黄不头秃 | 来源:发表于2023-06-08 02:14 被阅读0次

fetch是基于promise实现的,也是用于处理异步请求问题。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 
        fetch API 基本用法

        更加简单的数据获取方法,功能更大,更灵活,可以看作是xhr的升级版
        基于promise实现
        语法结构:
            fetch(url).then(fn2)
                      .then(fn3)
                      …
                      .catch(fn)
     -->

     <!-- 
         fetch 请求参数:
         常用配置选项:
         methods(string):http的请求方式,默认为GET(get,post,put,delete)
         body(string):http的请求参数
         headers(object):httpd的请求头,默认为{}

         get方式传递参数
            fetch("/path/num",{
                methods:"get"
            }).then(data=>{
                return data.text();
            }).then(ret=>{
                console.log(ret);
            });
         post方式传递参数
         fetch("/path/num",{
                methods:"post",
                body:'uame=list&psw=123',
                headers:{
                    'Comtent-Type':'application/x-www-form-urlencoded',
                }
            }).then(data=>{
                return data.text();
            }).then(ret=>{
                console.log(ret);
            });
      -->
     <script>
         fetch("./test.txt").then(function(data){
            //  text是fetch的一部分,返回promise实例对象
              return data.text();
         }).then(
             function(data){
                 console.log(data);
             }
         );
         fetch("https://www.baidu.com/search/error",{
             methods:'get',
             headers:{
                'Comtent-Type':'application/x-www-form-urlencoded',
             }
         }).then(function(data){
            //  text是fetch的一部分,返回promise实例对象
              return data.text();
         }).then(
             function(data){
                 console.log(data);
             }
         );
     </script>
     
</body>
</html>

fetch的响应结果处理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>Document</title>
</head>
<body>
    <!-- 
        text():将返回处理成字符串类型的
        json():返回结果和JSON.parse(responseText)一样
     -->
     <script>
         fetch('./text1.json').then(function(data){
             return data.json();
         }).then(function(data){
             console.log(data);
         });
     </script>
     
</body>
</html>

相关文章

网友评论

      本文标题:fetch API的基本使用方法

      本文链接:https://www.haomeiwen.com/subject/dllpedtx.html