马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
Javaweb-Ajax
一、Ajax简介
AJAX 全称为 Asynchronous JavaScript And XML,就是异步的 JS 和 XML。
通过 AJAX 可以在欣赏器中向服务器发送异步哀求,最大的上风:无革新获取数据。
AJAX 不是新的编程语言,而是一种将现有的尺度组合在一起利用的新方式。
二、Ajax的特点
(1)AJAX 的长处
- 可以无需革新页面而与服务器端举行通讯。
- 允许你根据用户变瞎搅更新部分页面内容。
(2)Ajax的缺点
- 没有欣赏汗青,不能回退
- 存在跨域题目(同源)
- SEO 不友好
三、原生Ajax
1、XMLHttpRequest,AJAX 的全部操纵都是通过该对象举行的。
2、当前端想设置自界说的哀求头时,必要让后端设置相应头
- //表示接收任意类型的请求
- app.all('/server', (request, response) => {
- //响应头 允许跨域 运行自定义响应头
- 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) 创建 XMLHttpRequest 对象
- var xhr = new XMLHttpRequest();
- 2) 设置请求信息
- xhr.open(method, url);
- //可以设置请求头,一般不设置
- xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- 3) 发送请求
- xhr.send(body) //get 请求不传 body 参数,只有 post 请求使用
- 4) 接收响应
- //xhr.responseXML 接收 xml 格式的响应数据
- //xhr.responseText 接收文本格式的响应数据
- xhr.onreadystatechange = function (){
- if(xhr.readyState == 4 && xhr.status == 200){
- var text = xhr.responseText;
- console.log(text);
- }}
复制代码 (1)Get方式
- //绑定事件
- btn.onclick = function () {
- //1. 创建对象
- const xhr = new XMLHttpRequest();
- //2. 初始化 设置请求方法和 url
- xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
- //3. 发送
- xhr.send();
- //4. 事件绑定 处理服务端返回的结果
- // on when 当....时候
- // readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4
- // change 改变
- xhr.onreadystatechange = function () {
- //判断 (服务端返回了所有的结果)
- if (xhr.readyState === 4) {
- //判断响应状态码 200 404 403 401 500
- // 2xx 成功
- if (xhr.status >= 200 && xhr.status < 300) {
- //处理结果 行 头 空行 体
- //响应
- // console.log(xhr.status);//状态码
- // console.log(xhr.statusText);//状态字符串
- // console.log(xhr.getAllResponseHeaders());//所有响应头
- // console.log(xhr.response);//响应体
- //设置 result 的文本
- result.innerHTML = xhr.response;
- } else {}
- }
- }
- }
复制代码 (2)Post方式
- //绑定事件
- result.addEventListener("mouseover", function(){
- //1. 创建对象
- const xhr = new XMLHttpRequest();
- //2. 初始化 设置类型与 URL
- xhr.open('POST', 'http://127.0.0.1:8000/server');
- //设置请求头
- xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
- xhr.setRequestHeader('name','atguigu');
- //3. 发送
- xhr.send('a=100&b=200&c=300');
- // xhr.send('a:100&b:200&c:300');
- // xhr.send('1233211234567');
- //4. 事件绑定
- xhr.onreadystatechange = function(){
- //判断
- if(xhr.readyState === 4){
- if(xhr.status >= 200 && xhr.status < 300){
- //处理服务端返回的结果
- result.innerHTML = xhr.response;
- }
- }
- }
- });
复制代码 (3)办理ie缓存题目
题目:在一些欣赏器中(IE),由于缓存机制的存在,ajax 只会发送的第一次哀求,剩余多次哀求不会再发送给欣赏器而是直接加载缓存中的数据。
办理方式:欣赏器的缓存是根据 url地点来记载的,以是我们只必要修改 url 地点 即可制止缓存题目 xhr.open(“get”,“/testAJAX?t=”+Date.now());
(4)哀求超时与网络非常
当你的哀求时间过长,大概无网络时,举行的相应处置处罚
- btn.addEventListener('click', function(){
- const xhr = new XMLHttpRequest();
- //超时设置 2s 设置
- xhr.timeout = 2000;
- //超时回调
- xhr.ontimeout = function(){
- alert("网络异常, 请稍后重试!!");
- }
- //网络异常回调
- xhr.onerror = function(){
- alert("你的网络似乎出了一些问题!");
- }
- xhr.open("GET",'http://127.0.0.1:8000/delay');
- xhr.send();
- xhr.onreadystatechange = function(){
- if(xhr.readyState === 4){
- if(xhr.status >= 200 && xhr.status< 300){
- result.innerHTML = xhr.response;
- }
- }
- }
- })
复制代码 (5)取消哀求
在哀求发出去后但是未相应完成时可以举行取消哀求操纵
- let x = null;
- btns[0].onclick = function(){
- x = new XMLHttpRequest();
- x.open("GET",'http://127.0.0.1:8000/delay');
- x.send();
- }
- // abort
- btns[1].onclick = function(){
- x.abort();
- }
复制代码 (6)重复哀求题目
利用之前取消哀求知识点,当我点击时判定之前哀求是否在发送中,如果是,则制止哀求
- btns[0].onclick = function(){
- //判断标识变量
- if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求
- x = new XMLHttpRequest();
- //修改 标识变量的值
- isSending = true;
- x.open("GET",'http://127.0.0.1:8000/delay');
- x.send();
- x.onreadystatechange = function(){
- if(x.readyState === 4){
- //修改标识变量
- isSending = false;
- }
- }
- }
- ————————————————
- 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
-
- 原文链接:https://blog.csdn.net/m0_72131231/article/details/140346480btns[0].onclick = function(){
- //判断标识变量
- if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求
- x = new XMLHttpRequest();
- //修改 标识变量的值
- isSending = true;
- x.open("GET",'http://127.0.0.1:8000/delay');
- x.send();
- x.onreadystatechange = function(){
- if(x.readyState === 4){
- //修改标识变量
- isSending = false;
- }
- }
- }
复制代码 五、常见三种Ajax哀求
1、jQuery发送AJAX哀求
jQuery有三种发送哀求方法:
当你只是简单的哀求数据,可以直接利用前两种方式哀求,当你必要设置的东西较多的时间,可以利用$.ajax()方法
(1)$.get()
- $('button').eq(0).click(function(){
- $.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
- console.log(data);
- },'json');
- });
复制代码 (2)$.post()
- $('button').eq(1).click(function(){
- $.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
- console.log(data);
- });
- });
复制代码 (3)$.ajax
- $('button').eq(2).click(function(){
- $.ajax({
- //url
- url: 'http://127.0.0.1:8000/jquery-server',
- //参数
- data: {a:100, b:200},
- //请求类型
- type: 'GET',
- //响应体结果
- dataType: 'json',
- //成功的回调
- success: function(data){
- console.log(data);
- },
- //超时时间
- timeout: 2000,
- //失败的回调
- error: function(){
- console.log('出错啦!!');
- },
- //头信息
- headers: {
- c:300,
- d:400
- }
- });
- });
复制代码 2、Axios发送AJAX哀求
(1)axios.get()
axios.get(url,data,params)
- //配置 baseURL
- axios.defaults.baseURL = 'http://127.0.0.1:8000';
- btns[0].onclick = function () {
- //GET 请求
- axios.get('/axios-server', {
- //url 参数
- params: {
- id: 100,
- vip: 7
- },
- //请求头信息
- headers: {
- name: 'atguigu',
- age: 20
- }
- }).then(value => {
- console.log(value);
- });
- }
复制代码 (2)axios.post()
axios.post(url,data,params)
- //配置 baseURL
- axios.defaults.baseURL = 'http://127.0.0.1:8000';
- btns[1].onclick = function () {
- axios.post('/axios-server', {
- username: 'admin',
- password: 'admin'
- }, {
- //url
- params: {
- id: 200,
- vip: 9
- },
- //请求头参数
- headers: {
- height: 180,
- weight: 180,
- }
- });
- }
复制代码 (3)axios() 常用
axios({})
- //配置 baseURL
- axios.defaults.baseURL = 'http://127.0.0.1:8000';
- btns[2].onclick = function () {
- axios({
- //请求方法
- method: 'POST',
- //url
- url: '/axios-server',
- //url参数
- params: {
- vip: 10,
- level: 30
- },
- //头信息,此部分如果使用自定义的头信息,需要服务端进行相应修改,正常不设置
- headers: {
- a: 100,
- b: 200
- },
- //请求体参数
- data: {
- username: 'admin',
- password: 'admin'
- }
- }).then(response => {
- //响应状态码
- console.log(response.status);
- //响应状态字符串
- console.log(response.statusText);
- //响应头信息
- console.log(response.headers);
- //响应体
- console.log(response.data);
- })
- }
复制代码 3、Fetch发送AJAX哀求
- 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);
- });
- }
复制代码 ``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] |