【发布时间】:2021-10-29 09:41:35
【问题描述】:
我需要将数据从 Java Servlet 后端传输到前端。数据以 JSON 格式传输,这就是我为实现它而编写的 servlet:
@WebServlet("/add")
public class AddElementServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
PrintWriter printWriter = resp.getWriter();
printWriter.write("{\"id\":1,\"content\":\"Hello, World!\"}");
printWriter.close();
}
}
该地址的网页显示的是 JSON 字符串。同时,前端没有得到传输的数据。我的猜测是使用 RequestDispatcher,但我看不到 .forward() 和 .redirect() 方法在这里有用。
那是我用来接收数据的前端版本。
第一个:
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8081/add'
}).then(function(data) {
alert('Data: '+ data + ' ' + data.id + ' ' + data.content);
$('.greeting-id').append(data.id);
$('.greeting-content').append(data.content);
});
});
第二个:
fetch('http://localhost:8081/add')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
我的错误在哪里,我该如何解决?
【问题讨论】:
-
访问前端时,浏览器控制台有什么消息吗?
-
Postman 有什么回应吗?
-
@PeterMmm,在第二种情况下,它只显示“解析的 json”。
-
@JanezKuhar,是的,我得到的回复与我预期的完全一样。
-
我相信 Postman 可以选择生成与您的请求等效的 JavaScript。见:Generating client code