一、Ajax介绍
什么是 AJAX?
- 全称:Asynchronous JavaScript And XML.
- 用于浏览器与服务器之间异步数据传输(HTTP请求)
- 它不是编程语言,是多种技术的组合而成,技术包括:HTML 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最核心的XMLHttpRequest(从 web 服务器请求数据)。
AJAX 如何工作
- 网页中发生一个事件(页面加载、按钮点击)
- 由 JavaScript 创建 XMLHttpRequest 对象
- XMLHttpRequest 对象向 web 服务器发送请求
- 服务器处理该请求
- 服务器将响应发送回网页
- 由 JavaScript 读取响应
- 由 JavaScript 执行正确的动作(比如更新页面)
二、Ajax优缺点
优:
- 不刷新页面更新网页
- 在页面加载后从服务器请求数据
- 在页面加载后从服务器接收数据
- 在后台向服务器发送数据
缺:
- 增加了设计和开发时间
- AJAX应用程序中的安全性较低,因为所有文件都是在客户端下载的。
三、Ajax使用
export const queryAjax=function(
url:string,
date:{},
){
// 创建 XMLHttpRequest 对象
const xhttp = new XMLHttpRequest();
// 前端设置是否带cookie
xhttp.withCredentials = true;
//请求体数据
let params= JSON.stringify(date);
// 发送请求
xhttp.open("POST", url);
//setRequestHeader添加HTTP 头部
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(params);
//设置响应数据格式
xhttp.responseType='json'
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//打印xhttp执行状态和响应体
console.log('send...onreadystatechange',this.readyState,this.response)
}
};
}
四、CORS 跨域资源分享(Cross-Origin Resource Sharing)。
1、普通跨域请求:只需服务器端设置Access-Control-Allow-Origin
2、带cookie跨域请求:前后端都需要进行设置
【前端设置】根据xhttp.withCredentials字段判断是否带有cookie
// 前端设置是否带cookie
xhttp.withCredentials = true;
【服务端设置】服务器端对于CORS的支持,主要是通过设置Access-Control-Allow-Origin来进行的。
/**
* @description:跨域请求
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*");// 设置允许跨域请求的域名
corsConfiguration.addAllowedHeader("*");// 设置允许的请求头
corsConfiguration.addAllowedMethod("*");// 允许的方法
corsConfiguration.setAllowCredentials(true);// 是否允许证书
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}