Ajax

发布时间 2023-10-13 10:58:08作者: dzw9

Asynchronous JavaScript And XML,异步的JavaScript和XML
数据交换:通过Ajax给服务器发送请求,并获取服务器响应的数据
异步交互:可以不重新加载整个页面情况下与服务器交换数据并更新部分网页

XMLHttpRequest对象属性

属性 描述
onreadystatechange 定义readystate属性发生变化时被调用的函数
readyState 保存状态,0未初始化,1服务器已连接,2收到请求,3正在处理请求,4请求已完成
responseText 以字符串返回响应数据
responseXML 以XML数据返回响应数据
status 返回请求状态,200 OK, 403 Forbidden,404 Not Found
statusText 返回状态文本
<!-- 原生方法 -->
<head>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
    <input type="button" value="获取数据" onclick="gatData()">
    <div id="div1"></div>
</body>
<script>
    function getData(){
        //1.创建XMLHttpRequest对象
        var xmlHttpRequest = new XMLHttpRequest();
        //2.发送异步请求
        xmlHttpRequest.open('GET','http://yapi.smart-xwork.cn/mock/169327/emp/list');
        xmlHttpRequest.send();  //发送请求
        //3.获取服务响应数据
        xmlHttpRequest.onreadystatechange = function(){
            if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){
                document.getElementById('div1').innerHTML = xmlHttpRequest.responseText;
            }
        }
    }
</script>
<!-- Axios -->
<body>
    <input type="button" value="获取数据GET" onclick="get()">
    <input type="button" value="删除数据POST" onclick="post()">
</body>
<script>
    function get(){
        axios({
            method:"get",
            url:"https://mock.apifox.cn/m1/3128855-0-default/emp/list"
        }).then(result=>{
            console.log(result.data);
        })
		
	<!-- 简写方法 -->
        axios.get("https://mock.apifox.cn/m1/3128855-0-default/emp/list").then(result=>{
            console.log(result.data);
        })
    }
<!-- post请求需要id -->
    function post(){
        axios({
            method:"post",
            data:"id=1",
            url:"https://mock.apifox.cn/m1/3128855-0-default/emp/deleteById"
        }).then(result=>{
            console.log(result.data);
        })
    }
</script>

Axios请求方式别名
axios.get(url,config)
axios.delete(url,config)
axios.post(url,data,config)
axios.put(url,data,config)