![](/img/trans.png)
[英]How to use jQuery to post JSON data to a Struts2 Action class
[英]JSON Jquery to Struts2 action
我想將JSON對象從Javscript發送到Struts2 Action。
示例JSON對象
{
"lists":["list1","list2","list3","list4","list5"],
"maps": {
"key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1"
},
"number1":123456789,
"numberarray1":[1,2,3,4,5,6,7,8,9],
"string1":"A",
"stringarray1":["A1","B1"]
}
我的Jquery Ajax
$.ajax({
type: 'POST',
url: 'json/JSON.action',
data: JSON.stringify(data),
dataType: 'json',
async: false ,
contentType: 'application/json; charset=utf-8',
success: function(){window.alert('Done');}
});
Struts.xml配置
<action name="JSON" class="com.actions.json.JsonAction" method="getJSON">
<result type="json"/>
</action>
我的動作類
public class JsonAction extends ActionSupport {
private String data;
public String getJSON() {
return ActionSupport.SUCCESS;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
我的問題是如何在Action Class中接收JSON對象。
注意:POST OF JSON對象成功..我只是不知道如何通過Action Class接收它..請幫助謝謝
struts.xml
條目中有一個拼寫錯誤 struts.xml
定義tile結果和攔截器。 請看這個鏈接 data
密鑰。 所以它總是空的。 因為json被表示為對象。 您需要以這種方式將JSON轉換為Java對象。 方法1。
為lists,maps,number1,numberarray1,string1
等創建setter。 在此鏈接的頂部,定義了執行此操作的方式。 然后,您可以通過這種方式訪問所有變量。
方法2.在你的javascript中定義一個新對象。
var sentData ={};
sentData ["sentData "] = data;
// And in your ajax call ,
data: JSON.stringify(sentData),
在你的動作類中,為此創建getter和setter。
Map<K.V> sentData = new HashMap<K,V>();
這將為您提供整個json對象作為Map。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.