将值从一个JSP页传递到另一个JSP页,并从第一个JSP返回响应数据[duplicate]

whhtz7ly  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(99)

此问题在此处已有答案

How should I use servlets and Ajax?(7个答案)
上个月关门了。
下面是我的first.jsp,我应该从其中使用 AJAX 调用second.jsp页面...我需要从first.jsp页面传递一个值到second.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页?

iibxawm4

iibxawm41#

在第一个. jsp文件中,尝试使用$.post(更合适)。

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

在第二个. jsp文件中,现在可以获得如下所示的“name”变量

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());
}
%>
vql8enpb

vql8enpb2#

那么,您已经创建了客户端接口,创建了服务器端逻辑来处理这些页面了吗?
你必须有服务器端逻辑来接收页面请求并用你的JSP页面来响应。以及响应你 AJAX 调用。你将需要创建Servlet,或者设置一个Web应用框架,如Spring WebMVC,JSF,Struts等。

相关问题