springboot学习之如何使用jQuery调用 RESTful Web服务
- 学习目标
- 学习环境
- 学习内容
- index.html页面
- hello.js文件
- 学习总结
学习目标
学习使用Jquery调用一个基于Spring的RESTful web服务接口。官方文档上写的是服务接口实现需要参考“ Building a RESTful Web Service with CORS”章节,我今天先不研究使用CORS实现的服务端,还是使用之前的服务“springboot学习之构建 RESTful Web服务”并借助Nginx(解决跨域)实现。
新建一个index.html,页面引入Jquery,访问如下接口:
http://127.0.0.1:8080/gs-rest-service/greeting
复制
服务返回一个json数据:
{"id":1,"content":"Hello, World!"}
复制
学习环境
nginx-1.21.5
idea
maven3.6.3
jdk1.8
学习内容
index.html页面
<!DOCTYPE html> <html> <head> <title>Hello jQuery</title> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script src="hello.js"></script> </head> <body> <div> <p class="greeting-id">The ID is </p> <p class="greeting-content">The content is </p> </div> </body> </html>
复制
hello.js文件
$(document).ready(function() { $.ajax({ url: "http://127.0.0.1:8081/gs-rest-service/greeting" }).then(function(data) { $('.greeting-id').append(data.id); $('.greeting-content').append(data.content); }); });
复制
nginx配置
upstream gs-rest-service { server 127.0.0.1:8080; } server { listen 8081; server_name 127.0.0.1; location /gs-rest-service { proxy_pass http://gs-rest-service; } # index.html和hello.js文件都放在E盘csdn目录下 location / { root E:\csdn; index index.html index.htm; } }
复制
测试
使用浏览器访问:http://127.0.0.1:8081/index.html,每刷新一次ID自增1,多刷新了几下所以显示结果如下:
学习总结
其实本文可以看成是前后端分离的应用场景。