简体   繁体   English

如何在JavaScript中使用struts标记

[英]How to use struts tag in javascript

I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value. 我正在尝试使用Ajax请求从Action获取值,但是在使用javascript中的struts标记显示值时遇到了问题。

Javascript code: JavaScript代码:

 dojo.xhrPost({
            url: "dashboard"
            ,content: myParameterscomp
            , handle: function(response, ioargs) {

               if (ioargs.xhr.status == 200)
               {
                   var data = "<s:property value='#request.consumptionData'/>"
                   console.log(data);
               }

             }

            ,error: function (data) {
                handleError(data.description);
            }           
        });

Java code: Java代码:

Map request = (Map)context.get("request");
 request.put("consumptionData",  43);

I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43 . 我在控制台而不是43上以<s:property value='#request.consumptionData'/>获取数据的值。 I'm using struts2. 我正在使用struts2。 My javascript code is in JSP file. 我的JavaScript代码在JSP文件中。 Could anyone please tell me how can I show the value? 谁能告诉我如何显示价值?

You seems to be calling /dashboard page via Ajax from your homepage. 您似乎正在从主页通过Ajax调用/ dashboard页面。 And expecting it to send you request attribute consumptionData. 并期望它向您发送请求属性consumptionData。 This won't work as your JSP does not contain required data. 由于您的JSP不包含必需的数据,因此无法使用。 You need to put data in JSP and then fetch the same in Ajax. 您需要将数据放入JSP,然后在Ajax中获取数据。 Convert your response to JSON. 将您的响应转换为JSON。 The simplest way of doing this would be to put following like of code in your Ajax response JSP. 最简单的方法是在您的Ajax响应JSP中放入以下类似代码。

Dashboard.jsp Dashboard.jsp

{"consumptionData": < "<s:property value='#request.consumptionData'/>"}

And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript. 在主页中,当您通过ajax加载此JSP时,可以解析此JSON输出并使用Javascript中的数据。

var json = JSON.parse(response);
var data = eval(json.consumptionData);

Code in browser accepts JSON. 浏览器中的代码接受JSON。 You could serialize you request as JSON and embed in you JavaScript file. 您可以将请求序列化为JSON并嵌入到JavaScript文件中。 For example: 例如:

var data = <%= toJson(request.get("consumptionData")) %>

If the data is simplely Integer values, you can even directly put the value in the code: 如果数据只是简单的Integer值,您甚至可以将值直接放入代码中:

var data = <%= request.get("consumptionData") %>

The syntax could be vary (I'm not familiar with struts tag), but the idea is the same. 语法可能会有所不同(我对struts标签不熟悉),但是想法是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM