首页 > 其他分享 >Ajax和Axios

Ajax和Axios

时间:2022-12-18 17:12:13浏览次数:31  
标签:function Axios resp Ajax xhttp ajax data localhost

 Ajax:

 

 

 

 

 

 

案例:(w3school有教程)

  前端代码:

 1   //1. 创建核心对象
 2     var xhttp;
 3     if (window.XMLHttpRequest) {
 4         xhttp = new XMLHttpRequest();
 5     } else {
 6         // code for IE6, IE5
 7         xhttp = new ActiveXObject("Microsoft.XMLHTTP");
 8     }
 9     //2. 发送请求
10     xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
11     xhttp.send();
12 
13     //3. 获取响应
14     xhttp.onreadystatechange = function() {
15         if (this.readyState == 4 && this.status == 200) {
16                执行...
17         }
18     };

 

 

后端代码:只要用resp返回一个布尔值给前端即可

response.getWriter().write("" + flag);

 


 

Axios:(简化Ajax书写及封装)

 

 

后端代码不变,只是前端代码中的书写方式改变

 

 

<script src="js/axios-0.18.0.js"></script>
<script>
    //1. get
    axios({//发请求
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {//相当于If(this.readyState==4&&this.status==200)
        if(resp.data == "true"){
      } else{
      } }) //2. post axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet", data:"username=zhangsan" }).then(function (resp) { alert(resp.data); }) </script>

 

another:

 

 

 简化上面的书写:(但可能不太利于观看)

 1 get方法:
 2 
 3 axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
 4   if(resp.data == "true"){
      } else{
      }
 5  })
1 post方法:
2 
3 axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
4         alert(resp.data);
5     })

标签:function,Axios,resp,Ajax,xhttp,ajax,data,localhost
From: https://www.cnblogs.com/changeyi/p/16990543.html

相关文章