ajax的请求以及传参方式,所有的ajax都是使用这一个全局对象
get请求
// get请求
let ajax = new XMLHttpRequest();
let getArticle = () => {
ajax.onload = () => {
console.log(ajax.response)
}
ajax.open("get", `http://localhost:8080/article/getArticle?articleId=${articleId.value}`)
ajax.send()
}
post请求,也可以使用username=admin&password以字符串的方式传入
// post请求, 参数要转为json字符串放在send函数中
let login = () => {
let username = document.querySelector(".username").value
let password = document.querySelector(".password").value
ajax.onload = () => {
let response = ajax.response
// 服务端会返回一个token令牌验证身份,将这个令牌存储在本地缓存中
if (response.data) {
localStorage.setItem("token", response.data)
}
}
ajax.responseType = "json"
ajax.open("post", `http://localhost:8080/user/login`)
// 默认请求方式为text/plain, 修改请求方式为json
ajax.setRequestHeader("Content-Type", "application/json;charset=utf-8")
ajax.send(JSON.stringify({
username,
password
}))
}
put请求, 参数要转为json字符串放在send函数中,这种方式类似于post
// put请求, 参数要转为json字符串放在send函数中
let updateUser = () => {
ajax.onload = () => {
let response = ajax.response
console.log(response)
}
ajax.responseType = "json"
ajax.open("put", `http://localhost:8080/user/update`)
// 设置token
ajax.setRequestHeader("Authentication", localStorage.getItem("token"))
ajax.setRequestHeader("Content-Type", "application/json;charset=utf-8")
ajax.send(JSON.stringify({
username: "admin3",
password: "123456",
phoneNumber: "15071094833",
email: "279761649@qq.com"
}))
}
delete请求
// delete请求, 参数放在请求路径中
let deleteTag = () => {
ajax.onload = () => {
let response = ajax.response
console.log(response)
}
ajax.open("delete", `http://localhost:8080/tag/delete/1`)
// 设置token
ajax.send()
}
接下来讲讲ajxa的监听方式,上面已经讲过使用onload的方式监听
另外一种方式是使用onreadystatechange的方式监听,当ajxa的状态被改变时,就会自动监听,
第一个状态不会被执行,ajax对象创建在全局中
let getArticle = () => {
ajax.onreadystatechange = () => {
if(ajax.readyState == 0) {
console.log("ajax对象创建")
console.log(ajax.status)
}
if(ajax.readyState == 1) {
console.log("send发送中")
}
if(ajax.readyState == 2) {
console.log("send发送完成")
}
if(ajax.readyState == 3) {
console.log("解析响应内容中")
}
if(ajax.readyState == 4) {
console.log("解析数据完成")
}
ajax.onabort() //取消请求
ajax.onloaded = function() {
console.log("无论成功或者失败都执行")
}
ajax.onerror = function() {
console.log("请求超时")
}
ajax设置请求格式
ajax.setRequestHeader("Content-Type", "text/plain") //文本格式
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") //表单提交
ajax.setRequestHeader("Content-Type", "application/json") //json格式
ajax.setRequestHeader("Content-Type", "form-data") //表单提交
通过ajax.upload.onprogress事件监听上传
<input type="file" class="file">
<p class="progress"></p>
<button onclick="uploadFile()">上传文件</button>
let ajax = new XMLHttpRequest();
let file = document.querySelector(".file")
let progress = document.querySelector(".progress")
let uploadFile = (event) => {
let formdate = new FormData()
formdate.append("file", file.files[0])
ajax.onload = () => {
console.log(ajax.response)
}
ajax.upload.onprogress = (event) => {
progress.innerHTML = (event.loaded / event.total * 100).toFixed(2) + "%"
};
ajax.open("post", "http://localhost:8080/file/uploadSingleFile")
ajax.send(formdate)
}
在浏览器发送ajax请求可能会触发浏览器的同源策略,阻止ajax请求,浏览器的URL地址和服务器满足以下其中一个请求即可
1. 协议不一致
2.ip地址不一致
3.端口号不一致
后端处理跨域请求
@Configuration
public class WebMvConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")// 设置跨域的路径
.allowedOriginPatterns("*") // 设置允许跨域的域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 设置允许的请求方法
.allowedHeaders("*") // 设置允许的请求头
.allowCredentials(true); // 设置是否允许证书
}
}