[英]How to pass InputStream value in Struts 2 action class to Ajax in JSP page and convert the value into JSON Array
我想將 JSON 數組從 Struts 2 動作類傳遞到 JSP 頁面。 我正在嘗試將數據集作為字符串發送。 我想知道的是,如何在 JavaScript 中讀取這些數據。
這是我在Action
類中的方法:
private InputStream inputStream;
/* getter and setter*/
public String getClientMilestone() throws DAOTransientException, DBConfigException{
PaymentScheduleDao paymentScheduleDao = new PaymentScheduleDao();
List <PaymentMilestone> paymentScheduleInfo = paymentScheduleDao.getClientMilestoneInfo(projectId);
String result = "[";
for(int i=0; i<paymentScheduleInfo.size(); i++){
result += "{"+"'"+"item"+i+"' : {"+ "'"+"milestoneName"+ "'"+":"+"'"+paymentScheduleInfo.get(i).getMilestone_name()+"'"+"}"+"},";
}
result += "]";
System.out.println("result is "+result);
inputStream = new StringBufferInputStream(result);
return "success";
}
它打印如下:
result is [{'item0' : {'milestoneName':'milestone 1'}},{'item1' : {'milestoneName':'milestone 2'}}]
struts.xml
:
<package name="ClientMilestone" namespace="/" extends="struts-default">
<action name="getClientMilestone" class="packageName.PaymentScheduleAction" method="getClientMilestone">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
<result name="failure">./LandingPage.jsp</result>
<result name="error">./Error.jsp</result>
</action>
</package>
JSP中的JavaScript函數:
function createOrViewPs() {
var projectId = document.getElementById("projectId").value;
$.ajax({
method: "GET",
url: "getClientMilestone",
data: {"projectId" : projectId},
traditional: true,
success:
function(result){
var jsonArr = result;
for (var i=0; i<jsonArr.length; i++)
for (var name in jsonArr[i]) {
alert("Item name: "+name);
alert("Source: "+jsonArr[i][name].milestoneName);
}
},
error:
function(){
alert("fail");
}
});
}
因為您使用stream
結果類型從服務器返回 JSON 的字符串化版本(注意,該流結果類型可能不合適,見下文),您需要使用JSON.parse()將其解析為 JSON,如果您正在使用jQuery 更好地使用$.each
var jsonArr = JSON.parse(result);
$.each (jsonArr, function(index, value){
$.each (value, function(key, value){
console.log("Item name: "+key);
console.log("Source: "+value.milestoneName);
});
});
您做錯的是手動構建 json 。 您應該使用將 Java 對象序列化為 JSON 的工具。 Struts2 的包中有json-lib可用的 jar,可用於序列化為 json,或者如果您使用的是struts2-json-plugin
,則它具有內置的序列化程序。 如果您使用的是struts2-rest-plugin
那么您可以使用其他序列化程序,如Jackson 。 您選擇庫來序列化數據的方式超出了此答案的范圍。 您可以在 SO 和Struts 網站上找到許多示例。 他們中的大多數使用返回瀏覽器支持的JSON對象的json插件,即不需要解析,但是解析JSON對於避免錯誤和數據丟失很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.