2013-10-29 25 views
1

在JSP中,我可以使用下面的代碼從動作類中獲取JSON。有人可以告訴我,如果有一種方法可以在不使用Ajax的情況下從操作類接收響應(JSON)?將JSON傳遞給動作類中的JSP,而不使用struts中的Ajax

$.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);}     
}) 

UPDATE:

以下代碼中的作用類使用。

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。

回答

0

是的。你可以用正常的方式做。通過提交頁面,您可以到達動作類別並將您的回覆設置爲

response.setContentType("application/json"); 
+0

請參見上面的更新。 – user2300206

相關問題