如何在JavaScript中访问Servlet变量 [英] How to access a servlet variable inside javascript
问题描述
我有一个servlet,该servlet的变量包含一个JSON字符串.
I have a servlet which has a variable which holds a JSON string.
JSONObject obj = new JSONObject();
obj.put("parameter", jsonList);
request.setAttribute("jsonstring", obj.toString());
RequestDispatcher rd = request.getRequestDispatcher("/file.jsp");
rd.forward(request, response);
现在,我将请求和响应对象转发到包含JS文件的JSP页面. 我该如何访问JS文件中的 jsonstring 变量的值.因为我需要使用jQuery进一步解析JSON字符串.
Now I am forwarding my request and response objects to a JSP page which contains a JS file. How can I access the value of jsonstring variable inside the JS file.As I need to parse my JSON string further using jQuery.
我尝试在JS文件中执行此操作,就像在网上的一些帖子中看到的那样.但这似乎对我不起作用.
I tried doing this in my JS file as I saw in some of the posts online.But it seems like its not working for me.
var test = '<%=request.getAttribute("jsonstring")%>'
请指导我.谢谢.
推荐答案
如果JSP文件使用<script>
标记加载外部JavaScript文件,则如下所示:
If the JSP file uses a <script>
tag to load an external JavaScript file, something like this:
<script type="text/javascript" src="js/yourFile.js"></script>
然后它将不起作用.您拥有的是一个JSP脚本,它仅在JSP文件执行期间具有某些含义.该yourFile.js
文件不会在服务器端进行解析,因为它不需要被解析.只有浏览器会知道如何使用<script>
标记,并向服务器发出请求以加载JavaScript.
then it won't work. What you have is a JSP scriptlet which only means something during the execution of the JSP file. That yourFile.js
file won't be parsed server-side because it doesn't need to be. Only the browser will know what to do with the <script>
tag and issue a request to the server to load the JavaScript.
在这些情况下,您可以在JSP中执行以下操作:
In these cases what you can do is something like this inside your JSP:
<script type="text/javascript">
var test = <%=request.getAttribute("jsonstring")%>;
</script>
<script type="text/javascript" src="js/yourFile.js"/></script>
由于JSP脚本位于您的JSP文件中,因此实际上可以正确处理它,而是输出对象/数组的有效JSON,以存储在全局范围内的test
变量中,然后您可以在
Since the JSP scriptlet is inside your JSP file it now actually gets processed correctly, and instead outputs the valid JSON for the object/array to store in the globally scoped test
variable, which you can then refer to inside yourFile.js
.
这篇关于如何在JavaScript中访问Servlet变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!