ajax笔记

视频资料:

ajax(异步的JavaScript和xml)

  • ajax的使用:
    1. 创建 XMLHttpRequest 对象
      1. var xhttp;
      2. if (window.XMLHttpRequest) {
      3. xhttp = new XMLHttpRequest();
      4. } else {
      5. // code for IE6, IE5
      6. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      7. }
  1. 发送请求
    1. xhttp.open("GET/POST", "servlet", true);
    2. xhttp.send();
  • ajax的常用属性:
    onreadystatechange
    onreadystatechange属性可以在网页加载完成后自动调用ajax请求,具体代码如下:
    1. xhttp.onreadystatechange = function() {
    2. if (this.readyState == 4 && this.status == 200) {
    3. document.getElementById("demo").innerHTML = this.responseText;
    4. }
    5. };
    6. xhttp.open("GET", "ajax_info.txt", true);
    7. xhttp.send();

axios:

  • axios官网:
    www.axios-http.cn
  • axios的使用:
    1. html内引入axios
      • 使用 jsDelivr CDN:
        1. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  1. - 使用 unpkg CDN:
  1. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  1. 使用axios发送请求,并获得响应结果:
    1. axios({
    2. method:"get/post"
    3. url:""
    4. }).then(function(resp){
    5. alert(resp.data)
    6. })
  1. axios的带参发送请求:
    • 网页(前端):
      1. //get方式参数只能卸载url里
      2. axios({
      3. method:"get"
      4. url:"/xxx?xxx=xxx&xxx=xxx"
      5. }).then(function(resp){
      6. alert(resp.data)
      7. })
      8. //post方式可以写在单独的data里
      9. axios({
      10. method:"get"
      11. url:"/xxx"
      12. data:"xxx=xxx&xxx=xxx"
      13. }).then(function(resp){
      14. alert(resp.data)
      15. })
  1. - servlet(后端):
  1. //接收前端传的参
  2. String xxx = request.getParameter("xxx");
  3. //做业务
  4. xxxxxxxxxxxxxxxxxx;
  5. //给前端返回参数
  6. response.setContentType("text/html;charset=utf-8");
  7. response.getWriter().write("xxx");
  1. axios请求方法的别名使用:
    • get请求:
      1. axios.get("url").then(function(resp){
      2. alert(resp.data);
      3. })
  1. - post请求:
  1. axios.post("url","参数").then(function(resp){
  2. alert(resp.data);
  3. })
  1. ![QQ截图20220502201458.png](https://cdn.nlark.com/yuque/0/2022/png/28453019/1651493956868-68ebebd2-0eb2-45ae-b96a-7e3409162eb5.png#clientId=ucf20a060-063f-4&crop=0&crop=0&crop=1&crop=1&from=drop&id=ud06b6e50&margin=%5Bobject%20Object%5D&name=QQ%E6%88%AA%E5%9B%BE20220502201458.png&originHeight=431&originWidth=328&originalType=binary&ratio=1&rotation=0&showTitle=false&size=67097&status=done&style=none&taskId=u3debf91d-c76e-446d-8222-3e6482fe5f5&title=)