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

2, fetch,POST请求
  1. //POST上传请求
  2. <button>点击</button>
  3. <script>
  4. var btn = document.querySelector('button')
  5. btn.onclick = function(){
  6. fetch('https://www.XXX.com/ajax/echo.php',{ //请求的服务器地址
  7. body:"name=mumu&&age=20", //请求的数据
  8. // body:{name:"mumu",age:20}, //第二种请求数据的方法json
  9. method:"POST", //请求方法
  10. headers:{ //请求头信息
  11. 'Content-Type':'application/x-www-form-urlencoded' //用url编码形式处理数据
  12. // 'Content-Type':'application/json' //第二种请求头编写方式json
  13. }
  14. })
  15. .then(res=>res.text()) //请求得到的数据转换为text
  16. .then(res=>{
  17. console.log(res) //打印输出
  18. })
  19. .catch(err=>{ //错误打印
  20. console.log(err)
  21. })
  22. }
  23. </script>

3 解决跨域
  1. fetch('http://localhost:3000', {
  2. mode: 'no-cors'
  3. }).then(res => {
  4. console.log('response', res)
  5. return res.text()
  6. }).then(body => {
  7. console.log('body', body)
  8. })