簡體   English   中英

JSP Ajax Servlet - 在 JSP 中獲取返回值

[英]JSP Ajax Servlet - Get returned value in JSP

我有兩個表,當我單擊第一個表時會加載其中一個表。所以我在我的 JSP 中使用 Ajax 來執行此操作:

  $("#tablesorter-demo tr").click(function(){
        $('#tablesorter-demo tr').not(this).removeClass('hilite');
        $(this).toggleClass('hilite'); 
       
        $.ajax({
           type: "post",
           url: "gerer_cf_ad",
           data: "name=test",
           success: function(data){
            
           }
         });
    });

在我的 JAVA 中:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String  forward = "/geCfAd/acc_getes.jsp";
     
    try {
        if(request.getParameter("name") != null){
            codeCentrale = "5874";
            libelle = "CApes";
            request.setAttribute("codeCentrale ",codeCentrale );
            request.setAttribute("libelle",libelle);
                        }getServletContext().getRequestDispatcher(forward).forward(request, response);
    } catch (Exception e) {
        e.getMessage();
    }
}

所以,我想在我的 JSP 中獲取值:libelle 和 codeCentrale 以將其添加到 may 表中,但我不能..

我的表代碼:

 <td id="td_codeCentrale SPCentrale" > <% if(request.getAttribute("codeCentrale ") != null){
                                                                                out.print(request.getAttribute("codeCentrale "));
                                                                            } %></td>
                                    <td id="td_libelleCentrale" ><% if(request.getAttribute("libelle") !=null){
                                                                        out.print(request.getAttribute("libelle")); 
                                                                    }%></td>
            
    

您可以通過兩種方式獲得它。

1)您可以從請求或會話中獲取它

在 JSP 頁面中編寫以下代碼以獲取值。

String value = session.getAttribute("libelle"); OR
String value = request.getAttribute("libelle");

2)您可以在 Ajax 響應中傳遞值。

在 Servlet 上編寫以下代碼。

out.println(libelle);

在 Ajax 中,您將獲得數據作為響應。

$.ajax({
       type: "post",
       url: "gerer_caf_adherente",
       data: "name=test",
       success: function(data){
        alert(data);  // your response will print here.

       }
     });

您的 JSP 代碼在服務器端運行,您的 JS 代碼在客戶端運行。 它們不能直接通信,只能通過 HTTP 請求。

請求對象是表示單個請求的 Java 抽象。 在請求中保存屬性只是在服務器處理 HTTP 請求時傳遞數據的一種便捷方式,它會在請求完成后立即被丟棄,因此在 AJAX 之后您不會獲得請求屬性。但是,它沒有t 影響服務器對 HTTP 請求的響應,因此您可以在 Response 中打印數據。

要通過 AJAX 請求將信息從服務器傳遞到客戶端,您必須在響應中包含該信息。

因此,在 java 端,使用以下方法寫入數據作為響應:

out.println(libelle);

在 Javascript 中,您將能夠獲取數據作為響應

$.ajax({
   type: "post",
   url: "gerer_caf_adherente",
   data: "name=test",
   success: function(response){
    alert(response);  // you will see the data in alert, you can use it    anywhere
   }
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM