7.Javaweb-Ajax

[复制链接]
发表于 2026-1-15 08:06:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Javaweb-Ajax



一、Ajax简介

AJAX 全称为 Asynchronous JavaScript And XML,就是异步的 JS 和 XML。
通过 AJAX 可以在欣赏器中向服务器发送异步哀求,最大的上风:无革新获取数据。
AJAX 不是新的编程语言,而是一种将现有的尺度组合在一起利用的新方式。
二、Ajax的特点

(1)AJAX 的长处

  • 可以无需革新页面而与服务器端举行通讯。
  • 允许你根据用户变瞎搅更新部分页面内容。
(2)Ajax的缺点

  • 没有欣赏汗青,不能回退
  • 存在跨域题目(同源)
  • SEO 不友好
三、原生Ajax

1、XMLHttpRequest,AJAX 的全部操纵都是通过该对象举行的。
2、当前端想设置自界说的哀求头时,必要让后端设置相应头
  1. //表示接收任意类型的请求                                                       
  2. app.all('/server', (request, response) => {
  3. //响应头 允许跨域     运行自定义响应头
  4. response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Allow-Headers', '*');}
复制代码
3、ajax哀求状态:xhr.readyState
0:哀求未初始化,还没有调用 open()。
1:哀求已经创建,但是还没有发送,还没有调用 send()。
2:哀求已发送,正在处置处罚中(通常现在可以从相应中获取内容头)。
3:哀求在处置处罚中;通常相应中已有部分数据可用了,没有全部完成。
4:相应已完成;您可以获取并利用服务器的相应了
四、Ajax的利用

  1. 1) 创建 XMLHttpRequest 对象
  2. var xhr = new XMLHttpRequest();
  3. 2) 设置请求信息
  4. xhr.open(method, url);
  5. //可以设置请求头,一般不设置
  6. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7. 3) 发送请求
  8. xhr.send(body) //get 请求不传 body 参数,只有 post 请求使用
  9. 4) 接收响应
  10. //xhr.responseXML 接收 xml 格式的响应数据
  11. //xhr.responseText 接收文本格式的响应数据
  12. xhr.onreadystatechange = function (){
  13. if(xhr.readyState == 4 && xhr.status == 200){
  14. var text = xhr.responseText;
  15. console.log(text);
  16. }}
复制代码
(1)Get方式

  1. //绑定事件
  2. btn.onclick = function () {
  3.   //1. 创建对象
  4.   const xhr = new XMLHttpRequest();
  5.   //2. 初始化 设置请求方法和 url
  6.   xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
  7.   //3. 发送
  8.   xhr.send();
  9.   //4. 事件绑定 处理服务端返回的结果
  10.   // on  when 当....时候
  11.   // readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4
  12.   // change  改变
  13.   xhr.onreadystatechange = function () {
  14.     //判断 (服务端返回了所有的结果)
  15.     if (xhr.readyState === 4) {
  16.       //判断响应状态码 200  404  403 401 500
  17.       // 2xx 成功
  18.       if (xhr.status >= 200 && xhr.status < 300) {
  19.         //处理结果  行 头 空行 体
  20.         //响应
  21.         // console.log(xhr.status);//状态码
  22.         // console.log(xhr.statusText);//状态字符串
  23.         // console.log(xhr.getAllResponseHeaders());//所有响应头
  24.         // console.log(xhr.response);//响应体
  25.         //设置 result 的文本
  26.         result.innerHTML = xhr.response;
  27.       } else {}
  28.     }
  29.   }
  30. }
复制代码
(2)Post方式

  1. //绑定事件
  2.    result.addEventListener("mouseover", function(){
  3.        //1. 创建对象
  4.        const xhr = new XMLHttpRequest();
  5.        //2. 初始化 设置类型与 URL
  6.        xhr.open('POST', 'http://127.0.0.1:8000/server');
  7.        //设置请求头
  8.        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  9.        xhr.setRequestHeader('name','atguigu');
  10.        //3. 发送
  11.        xhr.send('a=100&b=200&c=300');
  12.        // xhr.send('a:100&b:200&c:300');
  13.        // xhr.send('1233211234567');
  14.        //4. 事件绑定
  15.        xhr.onreadystatechange = function(){
  16.            //判断
  17.            if(xhr.readyState === 4){
  18.                if(xhr.status >= 200 && xhr.status < 300){
  19.                    //处理服务端返回的结果
  20.                    result.innerHTML = xhr.response;
  21.                }
  22.            }
  23.        }
  24.    });
复制代码
(3)办理ie缓存题目

题目:在一些欣赏器中(IE),由于缓存机制的存在,ajax 只会发送的第一次哀求,剩余多次哀求不会再发送给欣赏器而是直接加载缓存中的数据。
办理方式:欣赏器的缓存是根据 url地点来记载的,以是我们只必要修改 url 地点 即可制止缓存题目 xhr.open(“get”,“/testAJAX?t=”+Date.now());
(4)哀求超时与网络非常

当你的哀求时间过长,大概无网络时,举行的相应处置处罚
  1. btn.addEventListener('click', function(){
  2.          const xhr = new XMLHttpRequest();
  3.          //超时设置 2s 设置
  4.          xhr.timeout = 2000;
  5.          //超时回调
  6.          xhr.ontimeout = function(){
  7.              alert("网络异常, 请稍后重试!!");
  8.          }
  9.          //网络异常回调
  10.          xhr.onerror = function(){
  11.              alert("你的网络似乎出了一些问题!");
  12.          }
  13.          xhr.open("GET",'http://127.0.0.1:8000/delay');
  14.          xhr.send();
  15.          xhr.onreadystatechange = function(){
  16.              if(xhr.readyState === 4){
  17.                  if(xhr.status >= 200 && xhr.status< 300){
  18.                      result.innerHTML = xhr.response;
  19.                  }
  20.              }
  21.          }
  22.      })
复制代码
(5)取消哀求

在哀求发出去后但是未相应完成时可以举行取消哀求操纵
  1. let x = null;
  2. btns[0].onclick = function(){
  3.     x = new XMLHttpRequest();
  4.     x.open("GET",'http://127.0.0.1:8000/delay');
  5.     x.send();
  6. }
  7. // abort
  8. btns[1].onclick = function(){
  9.     x.abort();
  10. }
复制代码
(6)重复哀求题目

利用之前取消哀求知识点,当我点击时判定之前哀求是否在发送中,如果是,则制止哀求
  1. btns[0].onclick = function(){
  2.          //判断标识变量
  3.          if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求
  4.          x = new XMLHttpRequest();
  5.          //修改 标识变量的值
  6.          isSending = true;
  7.          x.open("GET",'http://127.0.0.1:8000/delay');
  8.          x.send();
  9.          x.onreadystatechange = function(){
  10.              if(x.readyState === 4){
  11.                  //修改标识变量
  12.                  isSending = false;
  13.              }
  14.          }
  15.      }
  16. ————————————————
  17.                             版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  18.                         
  19. 原文链接:https://blog.csdn.net/m0_72131231/article/details/140346480btns[0].onclick = function(){
  20.          //判断标识变量
  21.          if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求
  22.          x = new XMLHttpRequest();
  23.          //修改 标识变量的值
  24.          isSending = true;
  25.          x.open("GET",'http://127.0.0.1:8000/delay');
  26.          x.send();
  27.          x.onreadystatechange = function(){
  28.              if(x.readyState === 4){
  29.                  //修改标识变量
  30.                  isSending = false;
  31.              }
  32.          }
  33.      }
复制代码
五、常见三种Ajax哀求

1、jQuery发送AJAX哀求

jQuery有三种发送哀求方法:
当你只是简单的哀求数据,可以直接利用前两种方式哀求,当你必要设置的东西较多的时间,可以利用$.ajax()方法
(1)$.get()

  1. $('button').eq(0).click(function(){
  2.           $.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
  3.               console.log(data);
  4.           },'json');
  5.       });
复制代码
(2)$.post()

  1. $('button').eq(1).click(function(){
  2.           $.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
  3.               console.log(data);
  4.           });
  5.       });
复制代码
(3)$.ajax

  1. $('button').eq(2).click(function(){
  2.          $.ajax({
  3.              //url
  4.              url: 'http://127.0.0.1:8000/jquery-server',
  5.              //参数
  6.              data: {a:100, b:200},
  7.              //请求类型
  8.              type: 'GET',
  9.              //响应体结果
  10.              dataType: 'json',
  11.              //成功的回调
  12.              success: function(data){
  13.                  console.log(data);
  14.              },
  15.              //超时时间
  16.              timeout: 2000,
  17.              //失败的回调
  18.              error: function(){
  19.                  console.log('出错啦!!');
  20.              },
  21.              //头信息
  22.              headers: {
  23.                  c:300,
  24.                  d:400
  25.              }
  26.          });
  27.      });
复制代码
2、Axios发送AJAX哀求

(1)axios.get()

axios.get(url,data,params)
  1. //配置 baseURL
  2.   axios.defaults.baseURL = 'http://127.0.0.1:8000';
  3.   btns[0].onclick = function () {
  4.     //GET 请求
  5.     axios.get('/axios-server', {
  6.       //url 参数
  7.       params: {
  8.         id: 100,
  9.         vip: 7
  10.       },
  11.       //请求头信息
  12.       headers: {
  13.         name: 'atguigu',
  14.         age: 20
  15.       }
  16.     }).then(value => {
  17.       console.log(value);
  18.     });
  19.   }
复制代码
(2)axios.post()

axios.post(url,data,params)
  1. //配置 baseURL
  2.    axios.defaults.baseURL = 'http://127.0.0.1:8000';  
  3. btns[1].onclick = function () {
  4.      axios.post('/axios-server', {
  5.        username: 'admin',
  6.        password: 'admin'
  7.      }, {
  8.        //url
  9.        params: {
  10.          id: 200,
  11.          vip: 9
  12.        },
  13.        //请求头参数
  14.        headers: {
  15.          height: 180,
  16.          weight: 180,
  17.        }
  18.      });
  19.    }
复制代码
(3)axios() 常用

axios({})
  1. //配置 baseURL
  2.    axios.defaults.baseURL = 'http://127.0.0.1:8000';
  3. btns[2].onclick = function () {
  4.      axios({
  5.        //请求方法
  6.        method: 'POST',
  7.        //url
  8.        url: '/axios-server',
  9.        //url参数
  10.        params: {
  11.          vip: 10,
  12.          level: 30
  13.        },
  14.        //头信息,此部分如果使用自定义的头信息,需要服务端进行相应修改,正常不设置
  15.        headers: {
  16.          a: 100,
  17.          b: 200
  18.        },
  19.        //请求体参数
  20.        data: {
  21.          username: 'admin',
  22.          password: 'admin'
  23.        }
  24.      }).then(response => {
  25.        //响应状态码
  26.        console.log(response.status);
  27.        //响应状态字符串
  28.        console.log(response.statusText);
  29.        //响应头信息
  30.        console.log(response.headers);
  31.        //响应体
  32.        console.log(response.data);
  33.      })
  34.    }
复制代码
3、Fetch发送AJAX哀求

  1. btn.onclick = function () {
  2.     fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
  3.       //请求方法
  4.       method: 'POST',
  5.       //请求头
  6.       headers: {
  7.         name: 'atguigu'
  8.       },
  9.       //请求体
  10.       body: 'username=admin&password=admin'
  11.     }).then(response => {
  12.       // return response.text();
  13.       return response.json();
  14.     }).then(response => {
  15.       console.log(response);
  16.     });
  17.   }
复制代码
``java
btn.onclick = function () {
fetch(‘http://127.0.0.1:8000/fetch-server?vip=10’, {
//哀求方法
method: ‘POST’,
//哀求头
headers: {
name: ‘atguigu’
},
//哀求体
body: ‘username=admin&password=admin’
}).then(response => {
// return response.text();
return response.json();
}).then(response => {
console.log(response);
});
}
[code][/code]
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表