• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

前后端调用Ajax 学习

武飞扬头像
yyds_it_huo
帮助3

1. Ajax

使用Ajax技术网页应用能够快速的将增量更新在用户界面上,而不需要重新加载整个页面,这使得程序能够更快的回应用户的操作。

1.1 Ajax特点

局部刷新,异步访问。

  1. 同步请求:浏览器发起请求到服务器,如果服务器没有响应,用户则无法获取页面数据,处于等待状态,不可以做其他操作。
  2. 异步请求:异步请求时,浏览器可以进行其他的操作,当ajax数据获取之后,信息在页面局部刷新,可以理解为多线程的操作方式。

1.2 Ajax异步原理

Ajax可以异步原理:中间有Ajax引擎
回调函数:服务器返回数据,通过回调函数通知用户。

2. 跨域问题

注解方式

@RestController
@RequestMapping("/axios")
@CrossOrigin  //解决跨域问题
public class AxiosController {

3. 前后端调用案例

3.1 前后端调用—入门案例

前端JS

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>Axios demo</h1>
		<script src="../js/axios.js"></script>
		<script>
			let url1="http://localhost:8080/axios/findStr"
			//promise是封装服务器返回值的对象
			axios.get(url1)
				.then(function(promise){
					console.log(promise.data)
				})
		</script>
	</body>
</html>
学新通

编辑AxiosController

package com.huo.demo1_Axios.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/axios")
@CrossOrigin  //解决跨域问题
public class AxiosController {
    @GetMapping("/findStr")
    public String findStr(){
        return "好的好的哈";
    }
}

结果:
学新通

3.2 前后端调用—带简单参数

编辑页面JS

	let url2="http://localhost:8080/axios/getUserById?id=100";
		axios.get(url2)
			.then(function(promise){
				console.log(promise.data)
			})

编辑AxiosController

@GetMapping("/getUserById")
    public String getUserById(Integer id){
        return "id:" id;
    }

结果:
学新通

3.3 前后端调用—简化操作

axios.defaults.baseURL="http://localhost:8080";
		let url1="/axios/findStr"
		axios.get(url1)
			.then(function(promise){
				console.log(promise.data)
			})

3.4 前后端调用—对象传参

编辑页面JS

//对象参数传递写法  利用API自动拼接参数
	let user={id: 100,name: "tomcat"};
	axios.get("/axios/findUser",{params: user})
		.then(function(promise){
			console.log(promise.data)
		})

编辑AxiosController

	@GetMapping("/findUser")
    public User getFindUser(User user){
        return  user;
    }

返回User对象
学新通

3.5 前后端调用—ResultFul结构

ResultFul的结构不区分请求类型,任意请求类型都可以通过ResultFul的结构发送数据。
编辑页面JS

//RestFul 结构 模板字符串写法
	let rest={id:100,name:"tomcat",age:99}
	axios.get(`/axios/result/${rest.id}/${rest.name}/${rest.age}`)
		.then(function(promise){
			console.log(promise.data)
		})

编辑AxiosController

	//对象方式接收参数
    @GetMapping("/result/{id}/{name}/{age}")
    public User result(User user){

        return user;
    }
    //单个属性值接收的方式使用 @PathVariable 注解
    /*@GetMapping("/result/{id}/{name}/{age}")
    public User result(@PathVariable Integer id,
                       @PathVariable String name,
                       @PathVariable Integer age){
        User user=new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        return user;
    }*/
学新通

返回user对象
学新通

3.5 前后端调用—Post提交方式

编辑页面JS

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>ajax post 请求</h1>
		<script src="../js/axios.js"></script>
		<script>
			axios.defaults.baseURL="http://localhost:8080"
			
			let user={id:100,name:"tomcatPost",age:99}
			axios.post("/axios/saveUser",user)
				.then(function(promise){
					console.log(promise.data)
				})
		</script>
	</body>
</html>
学新通

编辑AxiosController

	@PostMapping("/saveUser")
    public User saveUser(@RequestBody User user){
        return user;
    }

返回User对象
学新通
说明:前端代码传递的JS对象,而后端使用的是java对象,2种对象没有办法直接转化,需要转化为JSON进行传递,axios使用post请求时,自动将JS对象解析为JSON串。
注:@RequestBody 将JSON转化为Java对象
       @ResponseBody 将Java对象转化为JSON串

4. 跨域问题

浏览器的网址与Ajax请求的网址必须满足如下的要求:
     协议://域名:端口号必须相同
如果满足要求则是同域访问,如果不满足要求则是跨域访问。

5. Axios优化

5.1 回调地狱

业务中经常遇到A的数据来源B,B的数据来源C。以此类推,则形成了Ajax嵌套的结构。

<script>
	axios.defaults.baseURL="http://localhost:8080"
			
	let user={id:100,name:"哈哈哈",age:99}
	axios.post("/axios/saveUser",user)
		.then(function(promise){
			console.log(promise.data)
			let arg1=promise.data
					
			axios.post("/axios/xxxx",arg1)
				.then(function(promise2){
					console.log(promise2.data)
					let arg2 = promise2.data
							
					axios.post("/axios/xxx",arg2)
						.then(function(promise3){
							console.log(promise3)
						})
							
				})
		})
 </script>
学新通

axios函数方式

<script>
	axios.defaults.baseURL="http://localhost:8080"
	/* 	 1.定义一个函数
		规则:
			1. async 标识函数
			2. await 标识请求
			3. 2者必须同时出现
			4. 可以直接获取then中的回调函数promise */
	async function saveUser(){
		let user={id:100,name:"哈哈哈"}
				
		/* let promise=await axios.post("/axios/saveUser",user)
		console.log(promise.data) */
				
		let {data:result,status: code}=await axios.post("/axios/saveUser",user)
		console.log(result) //对象
		console.log(code)	//状态码
		}
			
		/*  2.调用函数  */
		saveUser()
 </script>
学新通

箭头函数写法

<script>
		/* 箭头函数写法
			1.去除function关键字
			2.参数与函数体之间使用=>连接
			3.如果只有一个参数,则参数括号可以省略
			4.箭头函数使用一般用于回调函数
			5.如果使用function关键字 则使用this时会产生歧义 */
			 
		let user2={id:100,name:"箭头函数"}
		axios.post("/axios/saveUser",user2)
			.then(promise => {
				console.log(promise.data)
			})
			
</script>

这篇好文章是转载于:编程之路

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 编程之路
  • 本文地址: /boutique/detail/tanhhfeckg
系列文章
更多 icon
同类精品
更多 icon
继续加载