用jQuery Ajax实现前端调用SpringBoot Rest风格API Spring Boot + MyBatis + MySQL RESTFul Client入门实例

本文基于:

Spring Boot + MyBatis + MySQL

RESTFul Client入门实例

首先配置Spring Boot应用允许跨域访问,否则会报错:{from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.},解决方案例如在接口上使用@CrossOrgin注解:

 1 @RestController
 2 public class UserController {
 3     
 4     @Autowired
 5     private UserMapper userMapper;
 6 
 7     @CrossOrigin
 8     @RequestMapping("/getUsers")
 9     public List<UserEntity> getUsers() {
10         List<UserEntity> users=userMapper.getAll();
11         return users;
12     }
13     
14     @RequestMapping("/getUser")
15     public UserEntity getUser(Long id) {
16         UserEntity user=userMapper.getOne(id);
17         return user;
18     }
19     
20     @RequestMapping("/add")
21     public void save(UserEntity user) {
22         userMapper.insert(user);
23     }
24     
25     @RequestMapping(value="update")
26     public void update(UserEntity user) {
27         userMapper.update(user);
28     }
29     
30     @RequestMapping(value="/delete/{id}")
31     public void delete(@PathVariable("id") Long id) {
32         userMapper.delete(id);
33     }
34     
35     
36 }

其他解决方案参考:《SpringBoot下如何配置实现跨域请求?》https://blog.csdn.net/Colton_Null/article/details/75195230

在VS Code中添加如下HTML文件:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>my rest api</title>
 6 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
 7 </script>
 8 <script>
 9 $(document).ready(function(){
10     $("button").click(function(){
11         $("#div1").load("http://localhost:8080/getUsers");
12     });
13 });
14 </script>
15 </head>
16 <body>
17 
18 <div id="div1"><h2>use jQuery AJAX change content</h2></div>
19 <button>outside content</button>
20 
21 </body>
22 </html>

其中11行"http://localhost:8080/getUsers"为rest api的url

结果:

可获取到Rest API传过来的JSON数据并在界面上显示。

猜你喜欢

转载自www.cnblogs.com/ratels/p/10288476.html