页面说明
复选框: name=“hobby” 口 篮球 口 排球 口 乒乓球
问题: 参数如何提交? hobby=篮球,排球,乒乓球
前端URL模式: http://localhost:8080/user/saveHobby?hobby=篮球,排球,乒乓球
解决代码:
@GetMapping("/saveHobby")
public String[] saveHobby(String[] hobby){
//String[] arrays = hobby.split(",");
//将字符串转化为数组,可以方便后续业务的调用
//return arrays;
return hobby;
}
运行结果:
Ajax 概念用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。
特点局部刷新,异步访问
同步请求
浏览器发起请求到服务器时,如果服务器没有响应,用户则无法获取页面数据,处于等待状态.不可以做其它的操作.
异步请求
异步请求时,浏览器可以进行其它的操作.当ajax数据获取之后,信息在页面的局部刷新. (可以理解为多线程操作方式)
Ajax为什么可以异步: 中间有Ajax引擎.
回调函数: 服务器返回数据,通过回调函数通知用户.
前后端异步调用入门案例1.导入三阶段的js包
2.前端js代码
入门案例
3.编辑AxiosController
package com.jt.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/axios")
@CrossOrigin
//http://localhost:8080/axios/findstr
public class AxiosController {
@GetMapping("/findstr")
public String findstr(){
return "牛逼";
}
}
运行结果:
前后端调用-带简单参数js代码
入门案例 let url2="http://localhost:8080/axios/getUserById?id=100"; axios.get(url2).then(function(result){ console.log(result.data) })
编辑AxiosController
@GetMapping("/getUserById")
public String findUserById(Integer id){
return "获取数据:"+id;
}
前后端调用-对象传参
js代码
入门案例
编辑AxiosController
@GetMapping("/finduser")
public User finduser(User user){
return user;
}
运行结果
前后端调用-ResultFul结构
js代码
//4.RestFul结构实现数据传递 第一种:简单操作
let rest1 = {id: 100,name: "tomcat"}
axios.get("/axios/result/"+rest1.id+"/"+rest1.name)
.then(function(promise){
console.log(promise.data)
})
let rest2 = {id: 100,name: "tomcat"}
axios.get(`/axios/result/${rest2.id}/${rest2.name}`)
//模板字符串 保证代码格式
let div = `
天青色等烟雨
而我在等你
炊烟袅袅升起
隔江千万里
`
编辑AxiosController
@GetMapping("/result/{id}/{name}}")
public User result(User user){
return user;
}
前端POST提交方式
js代码
axios-post案例
编辑AxiosController
@PostMapping("/saveUser")
public User saveUser(@RequestBody User user){
return user;
}
参数类型规范
- GET/DELETE 参数提交的方式一致POST/PUT 参数提交的方式一致restFul结构适用于所有的请求类型
浏览器的网址与Ajax请求的网址必须满足如下的要求: 协议://域名:端口号必须相同.
如果满足要求则是同域访问,如果不满足要求 则是跨域访问
同源策略练习题
练习1:
1. http://localhost:8080/xxx/xxx 浏览器地址
2. http://localhost:8080/yyy/yyy ajax请求地址 同域请求
练习2:
1. http://127.0.0.1:8080/xxx/xxx 浏览器地址
2. http://localhost:8080/yyy/yyy ajax请求地址 跨域请求 域名不同
练习3: 域名与IP映射
1. http://www.jt.com:8080/xxx/xxx 浏览器地址
2. http://10.8.8.9:8080/yyy/yyy ajax请求地址 跨域请求! 域名不同
练习4:
1. http://www.jt.com:80/xxx/xxx 浏览器地址
2. http://www.jt.com/yyy/yyy ajax请求地址 同域请求!!!
http协议默认80端口
练习5:
1. https://www.jt.com/xxx/xxx 浏览器地址
2. https://www.jt.com:443/yyy/yyy ajax请求地址 同域请求!!!
https协议默认端口443
练习6:
1. http://www.jt.com/xxx/xxx 浏览器地址
2. https://www.jt.com:443/yyy/yyy ajax请求地址 跨域请求
@CrossOrigin:解决跨域问题,前后端连接
@RequestBody:将json串转化为java对象
单词:defalults:默认
base:根基,底部
origin:起源



