2014-01-11 92 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应用程序框架之一。

相关问题