异步请求Ajax

基于白嫖尚硅谷B站视频: 尚硅谷Web前端Ajax教程初学者零基础入门到精通全套完整版(ajax2020最新版)

1 原生Ajax

1.1 简介

异步的js和xml,在浏览器中向服务器发送异步请求,无刷新获取数据。不是新的编程语言,而是现有标准组合在一起使用的新方式。
场景:百度关键字提醒、用户名重复检验、QQ空间说说。

1.2 xml简介

可扩展标记语言;设计被用来传输和存储数据;xml没有预定义标签。
已经被json取代。
说白了!就是键值对<key,value>

1.3 缺点

不能回退;存在跨域问题;SEO不友好(不能爬)

1.4 HTTP协议

超文本传输协议。

1.4.1 请求报文

  • 行:GET(POST等)/url路径/HTTP协议版本
  • 头:Host、COOKIE、Content-type、User-Agent
  • 空行:
  • 体:username=??&password=??

1.4.2 响应报文

  • 行:协议版本 / 相应状态码(404、200)/ 相应状态字符串
  • 头:和请求报文一样
  • 空行:
  • 体:<html></html>

1.5 node和express框架

Node.js 是一个开源与跨平台的 JavaScript 运行时环境。服务端的javascrip。
安装:官方网址,注意ubuntu安装要将其bin目录添加到path->/etc/profile。

express是极简web服务框架。安装:

npm i express

编写js脚本:

//1引入express
const express = require('express');
//2创建应用对象
const app=express();
//服务目录
app.all('/server',(request,response)=>{
	//设置允许跨域的域名,*代表允许任意域名跨域
	response.header( 'Access-Control-Allow-Origin' , '*');
	//允许的header类型
	response.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
	//跨域允许的请求方式
	response.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	// 可以带cookies
	response.header("Access-Control-Allow-Credentials", true);
	
	//返回数据
	response.send("console");
	console.log("访问了server");
});
//4监听端口
app.listen(8000,()=>{
	console.log("服务已经启动,8000端口监听...");
})

保存为express.js
运行:

node express01.js

访问本地:localhost:8000即可。

1.6 Ajax Get请求基本操作

注意服务端添加跨域访问:

//设置响应头,可以跨域
response.header( 'Access-Control-Allow-Origin' , '*')

前端访问JavaScript代码:

//1 创建对象
const xhr = new XMLHttpRequest();
//2 初始化 设置请求方法和url
xhr.open('GET','http://localhost:8000/server');
//3 发送
xhr.send();
//4 事件绑定 处理服务端返回的结果
xhr.onreadystatechange = function (){
   //服务器返回结果
   if (xhr.readyState===4){
   	//0: 请求未初始化
	//1: 服务器连接已建立
	//2: 请求已接收
	//3: 请求处理中
	//4: 请求已完成,且响应已就绪
       //状态码是2××表示成功
       if (xhr.status>=200 && xhr.status<300){
           //结果:行 头 空行 体
           console.log(xhr.status);//状态码
           console.log(xhr.statusText);//状态字符串
           console.log(xhr.getAllResponseHeaders());//响应头
           console.log(xhr.response);//响应体
       }
   }
}

1.7 Get访问request设置参数

//2 初始化 设置请求方法和url
xhr.open('GET','http://localhost:8000/server?a=100&b=200&c=300');

携带的参数为a=100;b=200;c=300

1.8 POST请求方式

xhr.open('POST','http://localhost:8000/server');

可以携带参数

//3 发送
xhr.send('string');

1.9 请求头的设置

xhr.setRequestHeader('Content-type','application...');

也可以自定义请求头

1.10 json数据

对于客户端传回来的json数据,获取方式:
1 手动转换

let data=JSON.parse(xhr.response);

2 设置默认获取的就是json格式的数据

xhr.responseType = 'json';

1.11 超时和网络异常

超时:

//超时设置
xhr.timeout = 2000;
xhr.ontimeout = function (){
	alert("网络异常!")
}

确保网络能够连接,但是服务端持续时间偏长。
网络异常:

//超时设置
xhr.onerror=function (){
	alert("网络异常");
}

1.12 取消请求

xhr.abort();

可以根据一些逻辑(回调函数)来取消请求。

1.13 单用户重复请求问题

设置标识变量锁。

2 JQuery中的ajax

需要在head标签里面加上

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

2.1 Get

$('button').eq(0).click(function (){
   $.get('http://localhost:8000/server',{a:100},function (data){
       console.log(data);
   },'json')
})

传连接、给参数、返回data使用、响应体的类型。

2.2 post请求

$('button').eq(1).click(function (){
      $.post('http://localhost:8000/server',{a:100},function (data){
          console.log(data);
      },'json')
})

2.3 通用的ajax方法来交互

$('button').eq(2).click(function (){
            $.ajax({
                //url
                url: 'http://localhost:8000/server',
                //参数
                data: {a:100, b:200},
                //请求类型
                type: 'POST',
                //响应体结果
                dataType: 'json',
                //超时
                timeout: 1000,
                //成功的回调
                success: function (data){
                    console.log(data);
                },
                //失败的回调
                error: function (){
                    console.log("出错!")
                }
            });
        })

3 Axios

引用axios.js头

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.js"></script>

3.1 GET方式

3.1.1 GET方式1

axios.get('http://127.0.0.1:8000/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

3.1.2 GET方式2

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

处理GET请求参数教程

3.2 POST方式

// 通用方式请求
bt3.onclick = function (){
    axios.post('/user', {
    	firstName: 'Fred',
    	lastName: 'Flintstone'
  	}).then(function (response) {
    	console.log(response);
    }).catch(function (error) {
    	console.log(error);
    });
};

Spring Boot获取POST请求参数详解

4 fetch方式

fetch('http',{method:'POST',headers:……}).then(response=}{})

5 跨域

5.1 同源策略

为了安全,浏览器的策略,协议、域名、端口号必须完全相同。
违背同源策略就是跨域。

5.2 如何解决跨域

5.2.1 JSONP

非官方跨域解决方案,纯粹是靠程序的聪明才智,只支持GET请求方式
script标签本身就支持跨域
思想:在前端进行函数申明,利用script的src通过链接访问后端,后端返回的函数调用加实参(此处实参就是需要传递的参数)字符串,前端解析这个script的函数调用,进而执行加载,达到目的。

5.2.2 CORS

跨域资源共享。
在服务端设置:

response.header( 'Access-Control-Allow-Origin' , '*')
```deng
等。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值