赞
踩
Ajax 中文官网:https://jquery.cuishifeng.cn/jQuery.Ajax.html
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.8.RELEASE</version> <relativePath/> </parent> <groupId>cn.tedu</groupId> <artifactId>ajax</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ajax</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/tedu_ums?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
# Mybatis显示sql语句输出的配置
logging.level.cn.tedu.ajax.mapper=TRACE
@SpringBootApplication
@MapperScan("cn.tedu.ajax.mapper")
public class AjaxApplication {
public static void main(String[] args) {
SpringApplication.run(AjaxApplication.class, args);
}
}
要想在SpringBoot中使用ajax必须了解JSON格式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript"> let u={ id:10, username:"tom", skills:["c++","python","php"], dept:{id:1,name:"开发部"} } console.log(u.username) console.log(u.skills[2]); console.log(u.dept.name) </script> </body> </html>
//for循环遍历上面的 json 对象
for (let i = 0;i<j4.length;i++){
let book = j4[i];
//控制台输出
console.log(book.author)
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery.min.js" type="text/javascript"></script> </head> <body> <div id="msg">hehehe</div> <input id="btn" type="button" value="ajax"> <script type="text/javascript"> //jquery代码 //通过点击btn按钮,发送一个ajax请求 $("#btn").click(function(){ //开始发送ajax请求 $.ajax({ method:"get", url:"/test", dataType:"text",//表示这个ajax请求的返回值是字符串 success:function(result){//result表示控制器方法的返回值 //当ajax请求完成之后运行的代码 console.log(result); $("#msg").html(result); } }) }) </script> </body> </html>
@RestController //@RestController注解的含义是当前控制器类中每个控制器方法 // 都默认添加@ResponseBody注解 // SpringMvc框架会自动将@ResponseBody注解标记的方法的返回值转换为json格式 public class AjaxController { @GetMapping("/test") public String test(){ System.out.println("控制器方法执行"); /** * 因为这个类使用的@RestController注解 * 所以返回的"helloAjax"并不是视图名称,而就是字符串 * ajax方法可以接收这个字符串 */ return "helloAjax"; } }
public class JsonResult {
private int state;
private String message;
public JsonResult(){}
public JsonResult(int state, String message) {
this.state = state;
this.message = message;
}
//get\set\toString略
}
//$("#json")表示html页面上有个id为json的按钮
$("#json").click(function(){
$.ajax({
method: "get",
url:"/json",
dataType:"json",//表示本次请求控制器返回的信息格式是json格式
//实际上dataType属性的默认值就是json可以省略
success:function(result){//result是json格式的对象
console.log(result);
$("#msg").html(result.message)
}
})
})
@GetMapping("/json")
//当前控制器中,返回值类型为实体类的情况下
//这个实体类对象返回到ajax的方法中时,会自动转化为json格式
public JsonResult json(){
JsonResult r=new JsonResult(200,"查询完成!");
return r;
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery.min.js" type="text/javascript"></script> </head> <body> <!-- 如果确定发送异步请求, 那么form标签中的method和action属性也就没有意义了 --> <form method="post" action="/xxx"> 编号:<input id="state" name="state" type="text"><br> 信息:<input id="message" name="message" type="text"><br> <input id="send" type="submit" value="发送"> </form> <script type="text/javascript"> $("#send").click(function(){ let s=$("#state").val(); let m=$("#message").val(); $.ajax({ method:"post", url:"/param", data:{state:s,message:m}, success:function(result){ console.log(result.message); } }) //阻止表单提交 return false; }) </script> </body> </html>
@PostMapping("/param")
//ajax代码中data属性的写法为:data:{state:s,message:m},
//方法中参数名称必须和data指定的json格式对应
//SpringMvc会自动将s的值赋给int state,将m的值赋给String message
public JsonResult param(int state,String message){
System.out.println("state = " + state);
System.out.println("message = " + message);
JsonResult result=new JsonResult(state,message);
return result;
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery.min.js" type="text/javascript"></script> </head> <body> <!-- 如果确定发送异步请求, 那么form标签中的method和action属性也就没有意义了 --> <!-- 要想更方便的给ajax传递表单中的信息,先将form标签定义一个id属性 --> <form id="res" method="post" action="/xxx"> 编号:<input id="state" name="state" type="text"><br> 信息:<input id="message" name="message" type="text"><br> <input id="send" type="submit" value="发送"> </form> <script type="text/javascript"> $("#send").click(function(){ //let s=$("#state").val(); //let m=$("#message").val(); $.ajax({ method:"post", url:"/param", //利用form表单的id,调用serialize方法 //将表单中的所有信心,打包发送到springMvc //注意,serialize方法依据的是表单中的name属性, // 所以name属性要赋值才能使用serialize方法 data:$("#res").serialize(), success:function(result){ console.log(result.message); } }) //阻止表单提交 return false; }) </script> </body> </html>
@PostMapping("/param")
public JsonResult param(JsonResult result){
System.out.println(result);
return result;
}
var person={"name":"zhangsan","sex":"男","age":"24"}//json对象
alert(person.name);//zhangsan 控制台弹出person.name
alert(typeof person);//object 获取person的类型
var person='{"name":"zhangsan","sex":"男","age":"24"}';//json字符串
alert(person);//{"name":"zhangsan","sex":"男","age":"24"}
alert(typeof person);//string
var person='{"name":"zhangsan","sex":"男","age":"24"}';//json字符串
var personObject = JSON.parse(person);
alert(personObject.name);//zhangsan
var person={"name":"zhangsan","sex":"男","age":"24"};//json对象
var personString = JSON.stringify(person);
alert(personString);
<!-- Jackson JSON API-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.1</version>
</dependency>
2、转换
//集合转换成json字符串 需要一个第三方的框架进行转换
ObjectMapper om = new ObjectMapper();
//这个方法可以把任意对象转换为字符串 list 就是要转换的对象
String jsonStr = om.writeValueAsString(list);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。