2017-06-13 120 views
0

我想發送通過ajax請求定義的JSP java變量,它有可能嗎?JSP通過ajax發送Java變量

我的JSP:

<% 
    String fileName = (String)request.getAttribute(MatafConstants.PARAM_IMG_FILE_NAMES); 
%> 

然後我想給這個字符串:

$.ajax({ 
        url: "/some/urlServlet", 
        type: "get", //send it through get method 
        data: { 
        "statusID": status, 
        "test": '<%=fileName%>' //here is the param I send 
        }, 
        success: function(response) { 
        //Do Something 
        console.log(response); 
        }, 
        error: function(xhr) { 
        //Do Something to handle error 
        } 
}); 

我怎麼能送這個PARAM?或更大的問題,我可以在JavaScript中使用JSP的Java變量?

+0

與您當前的做法,會發生什麼? –

+0

是否要將JS代碼保存在與JSP相同的頁面上? –

+0

只是說,Ajax使用的是Javascript,客戶端沒有JSP。這意味着「fileName」在這一點上是一個常量(用'<%= ...%>'標籤輸出/寫入。在客戶端檢查源代碼,你會發現它會像''test':'your parameter'/ /這裏是我發送的參數' – AxelH

回答

1

您可以使用scriplet中的值創建隱藏字段,然後在Java Script中使用它的值。類似下面:

JSP代碼

<input type="hidden" id="fileName" value="<%=(String)request.getAttribute(MatafConstants.PARAM_IMG_FILE_NAMES)%>"> 

的Java腳本代碼

data: { 
    "statusID": status, 
    "test": document.getElementById("fileName").value; 
}, 
+0

如果它是一個數組?創建每個元素? –

+0

您在數組中有什麼類型的元素? –

+0

如果該請求只需要使用該值,則可以直接在'data.test'字段中完成。在這種情況下使用隱藏字段沒有什麼特別之處 – AxelH

0

答案是肯定的。並且您的請求看起來正確。但請確保您在啓動該變量的同一頁面中添加AJAX調用。

<jsp:declaration> 
    String name=null; 
    String role=null; 
    String company=null; 
</jsp:declaration> 
<jsp:scriptlet> 
    if(request.getSession().getAttribute("username")==null){ 
     response.sendRedirect("../login.jsp"); 
    } 
    else{ 
     name=(String)request.getSession().getAttribute("username"); 
     role= (String)request.getSession().getAttribute("role"); 
     company=(String)request.getSession().getAttribute("company"); 
    } 
</jsp:scriptlet> 

JavaScript中的同一頁上:

<script> 
      var name="<jsp:expression>name</jsp:expression>"; 
      var company="<jsp:expression>company </jsp:expression>"; 
</script>