ajax,fetch,axios学习笔记

ajax

  • 作用:通过js向服务器发送请求来加载数据

  • 解释:

    a:异步
    j:JavaScript
    a:and
    x:xml

xml是一种数据表示方法,但是过时了
现在一般用json表示

几种方式:

Xmlhttprequest(xhr小黄人)

fetch

axios

跨域问题CORSERROR

下面三个东西,只要有一个不一样,就是存在跨域问题

  1. 协议
  2. 域名
  3. 端口号

解决方法:在服务器里设置一个运行跨域的头

可以用注解

@CrossOrigin

![image-20221125115436102](/Users/yangstar/Library/Application Support/typora-user-images/image-20221125115436102.png)

xhr的使用

 <script>
        const btn=document.getElementById("btn")
        btn.onclick=()=>{
        //创建一个新的xhr对象
        const xhr= new XMLHttpRequest()

        //告诉ajax返回对象为json格式,设置响应体的类型
        xhr.responseType="json"

        //为xhr对象绑定一个load事件
        xhr.onload=function(){
            if(xhr.status===200){
            //xhr.response表示响应信息
            /*
            const user=JSON.parse(xhr.response)
            手动操作
            如果没有   xhr.responseType="json"的话要
            */
            // console.log(xhr.response);
            const res=xhr.response
            const ul =document.createElement("ul")
            root.appendChild(ul)
            
            }
         
        }

        //设置请求信息
        xhr.open("GET","http://localhost:8080/test/user")
        //发送请求
        xhr.send()
        }
        
    </script>
posted @ 2022-11-25 11:49  yangstar  阅读(15)  评论(0编辑  收藏  举报