调用 Java Servlet 逻辑而不定向到新页面



在我的网页上,我通过一个按钮向servlet发出GET请求。我的servlet从网络摄像头读取并保存图像文件(保存到"img/frame.jpg")。然后,我的网页包含一个脚本,每秒从此文件中读取一次,因此它会在网页上更新。

网页:

<html>
<body>
<img id='feed' src="img/frame.jpg" />
<form method="GET"
action="startCCTV.do">
<br><br>
<center>
<input type="SUBMIT"? value='Start'/>
</center>
</form>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="js/main.js"></script>
</body>

JavaScript(自问题回答后更新):

window.setInterval(function updateFrame() {
invokeServlet();
},  1000);
// Preload images.
function refreshImage() {
var image = new Image();
image.src = "img/frame.jpg?" + new Date().getTime();
image.onload = function() {
// Image exists and is loaded.
$("#feed").attr('src', "img/frame.jpg?" + new Date().getTime());
}    
}
// Send a GET request to the Servlet, to write a new image from the webcam.
function invokeServlet() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
refreshImage();
}   
};
xhttp.open("GET", "startCCTV.do", true);
xhttp.send();
}

我的 servlet 中确实有一个无限循环来连续写入新图像,因此图像将在网页上更新。但是,这似乎不是一个好方法(图像每 3 或 4 秒刷新一次,有时根本不显示)。我认为最好的方法是在我的updateFrame()GET 函数中循环我的 GET 请求,并让 servlet 为每个请求写入一个图像。

但是,我不知道如何在我的 Javascript 中发出此请求,一旦 servlet 完成其写入过程,就不会被重定向到 servlet 响应。

如何在不被重定向到新页面的情况下对我的 servlet 发出间歇性请求(即只是在我的页面上刷新图像)?

为避免加载时闪烁、丢失图像,您可以预加载新图像并在加载完成后显示。
如何做到这一点可以在其他答案中找到。

正如建议的那样,解决方案是使用 AJAX 调用。我实现了这一点如下:

// Send a GET request to the Servlet, to write a new image from the webcam.
function invokeServlet() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
refreshImage();
}   
};
xhttp.open("GET", "startCCTV.do", true);
xhttp.send();
}

我从我的setInterval方法中调用了这个invokeServlet方法。我已经更新了问题中的JavaScript以包含它。

最新更新