2016-08-03 111 views
2

我想在不刷新頁面的情況下在同一頁面中打印我的servlet的響應。我寫了這段代碼,但我不明白爲什麼它打開頁面:http://localhost:8080/..../NewServlet.do,而不是在同一頁面顯示結果。Servlet的響應沒有刷新JSP

 <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>"); 

     } 

回答

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; 
}); 
+0

沒有。它重新加載頁面:( – blinkettaro

+0

啊,現在我看到了它:首先,你的表單沒有id,但是你使用ID選擇器來獲取它 - 不能工作,在表單中添加id =「form1」'。 ,我會將腳本封裝到'$(document).ready(function(){...這裏是原始代碼...});',當然,當我們修改它時,DOM已經被構建。 –

+0

我修改了我的代碼(不是你寫的那個)添加id ='form1',它不起作用,然後我用你的代碼,它不工作,看起來javascritp代碼沒有被讀取或激活。 :/ – blinkettaro

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