2014-01-11 91 views
0

下面是我的first.jsp,我應該使用AJAX調用second.jsp頁面...並且我需要將值從first.jsp頁面傳遞給second.jsp頁面。將值從一個JSP頁面傳遞到另一個JSP頁面,並從第一個JSP頁面獲取響應數據

然後在second.jsp頁面使用該變量值和使用,使一個SELECT查詢和數據返回到first.jsp page

下面是我first.jsp page

<html> 
    <head> 
    </head> 
    <body>  
     <p><input type="radio" name="dish" value="Indian" id="radioButton"> Continental</input></p> 
     <p><label for="male" id="columnData">Male</label></p>  
     <script> 
      $(document).ready(function() { 
       $('#radioButton').click(function() { 
        alert($('#columnData').html()); 
        var name = $('#columnData').html();    
        $.ajax({ 
         type:"POST",  
         url: "second.jsp", 
         data:"name=" +name,   
         success: function(success) {         
         } 
        });     
       }); 
      }); 
     </script> 
    </body> 
</html> 

下面是我second.jsp page中,我需要從first.jsp中檢索該值並進行選擇查詢並將結果返回。

<html> 
    <head> 
     <title>SELECT Operation</title> 
    </head> 
    <body> 
    <sql:setDataSource var="snapshot" driver="org.postgresql.Driver" 
         url="jdbc:postgresql://localhost/postDB" 
         user="postgres" password="hello"/> 

    <sql:query dataSource="${snapshot}" var="result"> 
     // use the name variable value here passed from first.jsp page? 
     SELECT * from Employees where name = ?; 
    </sql:query> 
</body> 
</html> 

我不確定如何將值從一個JSP頁面傳遞到另一個JSP頁面,然後將second.jsp頁面的結果返回到first.jsp頁面?

回答

2

在您的first.jsp文件中,請嘗試使用$ .post(更合適)。

$.post("second.jsp", {'name': name}, 
     function(data) 
     { 
      alert("Result from second.jsp: " + data.name + " " + data.type); 
     } 
); 

在你second.jsp文件,你現在可以得到 「名」 變量這樣

request.getParameter("name") 

然後,執行查詢並返回結果

<%@page import="org.json.simple.JSONObject"%> 

<% 
if (request.getParameter("name") != null) 
{ 
    response.setContentType("application/json"); 

    ... your select query ... 

    JSONObject json = new JSONObject(); 
    ... put your sql data like this ... 
    json.put("name", "hello"); 
    json.put("type", "world"); 

    response.getWriter().write(json.toString()); 
} 
%> 
+0

感謝賈斯汀..我能夠使用你的建議正確地從我的first.jsp頁面調用second.jsp頁面。但正如你在我的second.jsp頁面中看到的那樣,我正在對數據庫進行SQL select查詢。所以它應該將數據變量中的first.jsp中的SELECT查詢響應返回給我?正確?如果是,那麼它不會發生。它將我完整的html代碼返回給我,而不是數據庫中的數據。任何想法有什麼不對? – AKIWEB

+0

如果您想返回選擇查詢的結果,請考慮使用JSON發回數據。這樣做,你可以找回所有數據在jquery(first.jsp) –

+0

謝謝賈斯汀。你能提供一個關於這個例子的例子以及對應於我的例子嗎?我最近開始與這個工作,所以不知道我應該做什麼改變?任何幫助將不勝感激。 – AKIWEB

0

所以你已經創建了你的客戶端接口,你創建了服務器端邏輯來處理這些頁面嗎?

您必須擁有服務器端邏輯才能接收頁面請求並使用JSP頁面進行響應。以及響應你的AJAX調用。您需要創建Servlet,或者設置Spring WebMVC,JSF,Struts等Web應用程序框架之一。

相關問題