WC *_*ini 5 java ajax jquery json struts2
我想将 JEON 数组从 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";
}
Run Code Online (Sandbox Code Playgroud)
它打印如下:
result is [{'item0' : {'milestoneName':'milestone 1'}},{'item1' : {'milestoneName':'milestone 2'}}]
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
因为您从服务器返回带有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);
});
});
Run Code Online (Sandbox Code Playgroud)
你做错的是手动构建 json 。您应该使用将 Java 对象序列化为 JSON 的工具。Struts2 包中有json-lib可用的 jar,可用于序列化为 json,或者如果您正在使用,struts2-json-plugin
那么它有内置的序列化器。如果您正在使用struts2-rest-plugin
那么您可以使用其他序列化器,例如Jackson。您选择库来序列化数据的方式超出了本答案的范围。您可以在 SO 和Struts 站点上找到许多示例。其中大多数使用 json 插件,该插件返回浏览器支持的 JSON 对象,即不需要解析,但是解析 JSON 有助于避免错误和数据丢失。
归档时间: |
|
查看次数: |
1011 次 |
最近记录: |