【问题标题】:Pass JSON to JSP from action class without using Ajax in struts将 JSON 从动作类传递给 JSP,而不在 struts 中使用 Ajax
【发布时间】:2013-10-29 18:59:50
【问题描述】:

在 JSP 中,我可以使用下面的代码从动作类中获取 JSON。有人可以告诉我是否有办法在不使用 Ajax 的情况下从动作类接收响应(JSON)?

$.ajax({
url:"/StrutsExample1/helloWorld.do",
data:params,
type: "post",
dataType:"json",
success:function(response){
          $.each(response,function(i){  
              $.each(response[i],function(key,value){
                 $('#info').html(key+" "+value);})
           })
},
    error:  function(e){ alert("fail " + e);}                   
})

更新:

在动作类中使用了以下代码。

response.setContentType("text/json; charset=utf-8");
JSONObject json = createJsonObject();  //to construct the JSON
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
return mapping.findForward("success");

在 struts-config.xml 中,我在动作映射中有以下内容:

<action path="/helloWorld" type="test.action.HelloWorldAction" name="helloWorldForm">
<forward name="success" path="/index.jsp" />

然后,在 JSP 文件中,不是像上面那样使用 Ajax 调用,它看起来像:

$(function(response){
   $.each(response,function(i){ 
              $.each(response[i],function(key,value){
                 $('#info').html(key+" "+value);})
           })
})

但是,执行时未定义键和值。 JSON 在动作类中正确构造。请帮忙指出如何将JSON传递给jsp。

【问题讨论】:

    标签: jquery ajax json jsp struts


    【解决方案1】:

    是的。你可以用正常的方式做。通过提交页面,您可以到达操作类并将您的响应设置为

    response.setContentType("application/json");
    

    【讨论】:

    • 这里不回答如何在不使用ajax的情况下在jsp中获取响应内容(如json字符串)。假设我没有要提交的表格。只是从 Action 到 jsp 的转发,文本(在响应中)要显示/解析(json 字符串)
    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2013-12-07
    • 1970-01-01
    • 2014-12-14
    • 2015-02-04
    • 1970-01-01
    • 2017-08-29
    • 2020-05-09
    相关资源
    最近更新 更多