收到错误消息,JSONArray[0] 不是 JSONObject,同时从 JSON 数组中获取对象(Java 代码行 #5)。
客户端的 jQuery
function setCosting(){
var costingArray = {};
costingArray = getCostingArray();
var costingData = JSON.stringify(costingArray);
alert(costingData);
$.ajax({
type:"POST",
url:"/costApp/budgetline.do?action=setCosting",
data:{"costingData": costingData},
datatype:'json',
success: function (msg) {
if (msg) {
alert('success');
}
},
error: function (msg) {
alert('error');
}
});
function getCostingArray() {
var rows = $("table tbody tr");
var dataset = [];
rows.each(function(i, row){
var rowset = {};
var $row = $(row);
rowset['travelType'] = $row.find('#travelType').val();
rowset['staff'] = $row.find('#staff').val();
rowset['trip'] = $row.find('#trip').val();
dataset.push(rowset);
});
return dataset;
}
$('#save').click(function() {
setCosting();
});
Java 代码
Map mpVal = request.getParameterMap();
JSONObject rootObj = new JSONObject(mpVal);
JSONArray arrayObj = rootObj.getJSONArray("costingData");
for(int m=0; m<arrayObj.length(); m++){
**JSONObject costing = arrayObj.getJSONObject(m);**
System.out.println(costing.getInt("travelType"));
System.out.println(costing.getInt("staff"));
System.out.println(costing.getInt("trip"));
}
该数组包含一个具有以下值的元素:
[
{
"travelType": "1",
"staff": "red",
"trip": ""
},
{
"travelType": "2",
"staff": "blue",
"trip": ""
},
{
"travelType": "3",
"staff": "green",
"trip": ""
}
]
任何评论将不胜感激。