后端Controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello,%s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name" ,defaultValue = "World" ) String name){
return new Greeting(counter.incrementAndGet(),String.format(template,name));
}
}
前端:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
id:
<span id="1"></span><br>
content:
<span id="2"></span>
</center>
<script th:src="@{js/jquery-3.5.1.js}"></script>
<script>
//使用jquery
$.ajax({
type: "get",
url: "/greeting",
success: function (data) {
$("#1").text(data.id);
$("#2").text(data.content);
},
});
//原生(设置span的值用的是jquery)
// var xmlhttp;
// xmlhttp=new XMLHttpRequest();
// xmlhttp.onreadystatechange=function()
// {
// if (xmlhttp.readyState==4 && xmlhttp.status==200)
// {
// $("#1").text(JSON.parse(xmlhttp.responseText).id);
// $("#2").text(JSON.parse(xmlhttp.responseText).content);
// }
// }
// xmlhttp.open("GET","/greeting",true);
// xmlhttp.send();
</script>
</body>
</html>