使用ajax将数据从servlet发送到jsp

时间:2014-08-02 17:02:44

标签: java jquery ajax jsp servlets

这里我使用ajax request将数据从servlet发送到jsp。但是我没有从客户端的servlet获取任何值。这是我的代码

的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String s="msg";
    System.out.print("Servlet");
    response.setContentType("text/plain");
    PrintWriter out=response.getWriter();
    out.print(s);
    out.flush();
    out.close();
}

JSP

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

<title>Insert title here</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript">
function poll() {
    setTimeout(function () {
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/ajaxtest/testajax',
            success: function (data) {
               alert(data); //DatO ANY PROCESS HERE
               //document.getElementById("testid").value=data;
               //document.write(data)
            },
            complete: poll
        });
    }, 5000);
}
</script>
</head>
<body onload="poll()">
<form><input type="text" name="test" id="testid" value=""></form>
</body>
</html>

输出:

enter image description here 我在浏览器调试工具上看到空警报框和“找不到元素”。

3 个答案:

答案 0 :(得分:0)

您的代码对我来说很好。检查是否从jsp正确访问了jquery.js,并检查web.xml是否正确进行了servlet映射。 最好包括jquery.js的下面一行,少打扰一下:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

enter image description here

答案 1 :(得分:0)

在放置警报框之前,您应该设置数据。当前警报框未获取任何数据

答案 2 :(得分:-1)

response.setContentType(“ text / plain”)更改为response.setContentType(“ text / html”) 并确认您提供的URL。 只需输入您的“项目名称/ servlet名称”

相关问题