Servlet的响应没有刷新JSP

时间:2016-08-03 11:01:15

标签: java jquery ajax jsp servlets

我想在不刷新页面的情况下在同一页面中打印我的servlet的响应。我编写了这段代码,但我无法理解为什么它会打开页面:http://localhost:8080/..../NewServlet.do而不是在同一页面中显示结果。

       <html>
       <head>
       <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

  <script type="text/javascript">

  var form = $('#form1');
  form.submit(function () {

   $.ajax({
   type: form.attr('method'),
   url: form.attr('action'),
   data: form.serialize(),
   success: function (data) {
   var result=data;
   $('#result').attr("value",result);

      }
    });

    return false;
    });  </script>
  </head>
     <body>
     <form name=form1 action="NewServlet.do" method="post">
   <select id='choose' class='form-control' name='choose'>
<option value='prodotti'>Products</option>
<option value='login'>Objects</option>
 </select>
<button type='submit' class='btn btn-default' style="width:  40%;">SUBMIT</button>

     <div id='result'>
      ///  I want the servlet's response is placed here.
   </div>

    </form>
   </body>
   <html>

我的servlet

     protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");
        String i = request.getParameter("choose");
        PrintWriter out = response.getWriter();
        out.println("<br>"+i+"</br>");

      }

2 个答案:

答案 0 :(得分:3)

它实际上不是关于Java或JSP,而是关于JavaScript。尝试

form.submit(function (event) {
  event.preventDefault(); // magic!
  $.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
      var result=data;
      $('#result').attr("value",result);
    }
  });
  return false;
});

答案 1 :(得分:0)

试试这个: 在jsp中

<input class="help_button" id="help_button" type="button" onclick="showDetail()" value="Do Smth" />


   function showDetail() {

    $.ajax({
         url:'/yourServlet.cfm',
         data:{dataName:data},
        type: 'GET',
    })
    .done(function(result) {
        //here do smth with result 
  });
}

您的Servlet

response.setContentType("text/plain");
response.getWriter().print("responseData"); //----Sending response