我正在实施一个小型Web应用程序。每1秒钟,应处理用户输入,并在页面上显示结果(响应值)。
架构的代码如下,但是如何实现调用请求的定时器?
结果的显示不应该导致页面刷新 - 否则,文本框中的值将丢失。
**跟进[DUPLICATE] 问题不仅在于询问基于已用计时器的处理请求,还在于在获取一些“提交数据”后显示响应的端到端效果 - 这是在重复问题链接中缺失的,并且是基础被问到的问题。
JSP (Default.jsp)
<html>
<head></head>
<body>
<br /> Input: <input type="text" id="input" />
<div id="theResponse"></div>
</body>
</html>
JavaScript (MyScript.js)
$(document).ready(function() {
$('#input').blur(function(event) {
var name = $('#input').val();
$.get('MyServlet', {
input: inputData
}, function(responseText) {
$('#theResponse').text(responseText);
});
});
});
Servlet (MyServlet.java)
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String input= request.getParameter("input");
if (input.equals("")) {
input= "cannot be empty";
} else {
//do some work ...
input= "ACK";
}
response.setContentType("text/plain");
response.getWriter().write(input);
}
}
Web配置(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Landing page</display-name>
<welcome-file-list>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet/*</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:0)
我不确定但是你需要将setInterval
添加到你的js代码中,如下所示:
myFunction(){
$.get('MyServlet', {
input: inputData
}, function(responseText) {
$('#theResponse').text(responseText);
});
}
$(document).ready(function() {
$('#input').blur(function(event) {
var name = $('#input').val();
setInterval(myFunction,time You want );
});
});