我想发送我通过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
}
});我怎么才能发出这封信?或者更大的问题,我可以在JavaScript中使用java变量吗?
发布于 2017-06-13 08:57:13
您可以从scriplet创建带有值的隐藏字段,然后在Java脚本中使用它的值。如下所示:
JSP代码
<input type="hidden" id="fileName" value="<%=(String)request.getAttribute(MatafConstants.PARAM_IMG_FILE_NAMES)%>">Java脚本代码
data: {
"statusID": status,
"test": document.getElementById("fileName").value;
},发布于 2017-06-13 08:59:34
答案是肯定的。你的要求看起来是正确的。但是,请确保将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>https://stackoverflow.com/questions/44516657
复制相似问题