fetch的GET和POST请求

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

(先心疼jQuery一会)

在这里插入图片描述

步入正题,下面分别用GET请求和POST请求发送请求

1 , fetch,请求本地json文件
//GET请求
<button>点击获取</button>
<script>
      var btn = document.querySelector('button')
      btn.onclick = function(){
          fetch('list.json') //请求地址
          .then(res=>res.json()) //将请求到的数据转换为json js对象
          .then(res=>{   //输出数据
              console.log(res)
          })
      }
</script>
2, fetch,POST请求
//POST上传请求
<button>点击</button>

<script>
   var btn = document.querySelector('button')
   btn.onclick = function(){
       fetch('https://www.XXX.com/ajax/echo.php',{ //请求的服务器地址
           body:"name=mumu&&age=20",  //请求的数据
           // body:{name:"mumu",age:20}, //第二种请求数据的方法json
           method:"POST", //请求方法
           headers:{  //请求头信息
               'Content-Type':'application/x-www-form-urlencoded' //用url编码形式处理数据
               // 'Content-Type':'application/json' //第二种请求头编写方式json
           }
       })
       .then(res=>res.text()) //请求得到的数据转换为text
       .then(res=>{
           console.log(res)   //打印输出
       })
       .catch(err=>{    //错误打印
           console.log(err)
       })
   }
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44348028/article/details/108104296