【问题标题】:Send data from servlet to jsp using ajax [duplicate]使用ajax将数据从servlet发送到jsp [重复]
【发布时间】:2014-09-25 16:08:46
【问题描述】:

这里我使用 ajax 请求将数据从 servlet 发送到 jsp。但是我没有从客户端的 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>

输出:

在浏览器调试工具上出现空警报框和“未找到元素”。

【问题讨论】:

  • 请求是否正确发送?网络控制台说什么?
  • 我已经上传了输出截图
  • 你有注册的过滤器吗?
  • 不。这是我尝试的全部代码..
  • 只需在 servlet 的 post() 方法中放入一个 SOP 并确认 servlet 正在正确调用。只需使用url: 'testajax',

标签: java jquery ajax jsp servlets


【解决方案1】:

您的代码对我来说运行良好。检查您的 jquery.js 是否从 jsp 正确访问,并检查您的 web.xml 是否有正确的 servlet 映射。 最好为 jquery.js 包括以下行,少一件需要担心的事情:

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

【讨论】:

  • 我认为这是web.xml中的问题。因为我在eclipse中创建了这个项目而没有生成web.xml,之后我用web.xml检查了这段代码,它工作了。但在我以前的情况下我的 servlet 在注释的帮助下工作得很好,但我没有在客户端得到元素。我仍然不明白问题的根本原因..
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2013-05-27
      相关资源
      最近更新 更多