【问题标题】:use Ajax to call data from servlet使用 Ajax 从 servlet 调用数据
【发布时间】:2014-12-02 10:59:18
【问题描述】:

我知道这个问题可能以前被问过,但我似乎无法在上面找到遮篷。

我正在尝试在加载页面时调用 servlet 方法,此时这是一个无限循环,因为每次 servlet 发布响应时,页面都会重新加载并再次调用 servlet,然后再次调用重新加载页面等等等。

我正在从 url 中收集一个 ID,然后在 servlet 中使用它来收集我需要的数据。 这是我目前正在使用的代码。

<form style="display:none;" action="ServletC" method="POST">
                <input type="hidden" name="hdn_parameter" value="<%= request.getParameter("productID")%>"/>
                <input type="submit" id="btn_loadform" name="loadform" style="display: none;"/>
                <script>

                        document.getElementById('btn_loadform').click();
                </script>
            </form>

我在整个页面中都得到了几段这样的代码

<img id="picture_img" class="" style="width:300px;" src="${ImageResponse}" />

以下代码在我的 servlet 上

if (request.getParameter("loadform") != null)
    {
            int productID = Integer.parseInt(request.getParameter("hdn_parameter"));
            String link = "PictureDetail.jsp?productID=" + Integer.toString(productID);
            Product p = null;
             try 
             {
                  p = DBConnect.getProduct(productID);
             } 
             catch (SQLException ex) 
             {
                 Logger.getLogger(ServletC.class.getName()).log(Level.SEVERE, null, ex);
             }

            request.setAttribute("ImageResponse", p.getPath());
            request.setAttribute("TitleResponse", p.getName());
            request.setAttribute("DescriptionResponse", p.getDescription());
            request.setAttribute("PriceResponse", p.getPrice());
            loaded = true;
            RequestDispatcher dis = request.getRequestDispatcher(link);
            dis.forward(request, response);
    }

任何人都可以帮助我现在应该做些什么来实现这一点,而无需刷新页面,以便它能够顺利运行。

提前致谢。

【问题讨论】:

  • 如果你重定向页面然后在 ajax 中你会得到 response.i.e 实际的 HTML 代码。您将获得重定向页面 HTML。如果您想在不使用 ajax 的情况下重定向和加载该页面

标签: ajax jsp servlets


【解决方案1】:

点击该按钮发出的请求是正确的 http 请求,其响应自然会重新绘制页面。您必须在单击按钮时形成 AJAX 请求,解析成功时的响应,然后在页面上执行某些操作(使用解析的响应数据)。

【讨论】:

  • 你能告诉我具体怎么做吗,我对ajax一无所知
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
相关资源
最近更新 更多