[英]Ajax send JSON array to servlet
我制作了一個表格,該表格匯總了表格的行和列。 但是現在我想在Servlet中計算總和,我將帶有JSON的列和行的數組發送到Servlet。 一切正常。 但是現在的問題是,如何計算servlet中行和列的總和並發回?
這是我的代碼:
$(document).on('change',function(){
var columnValues={}, rowValues={};
$("#sum_table tr").each(function(rowIndex){
$("td input", $(this)).each(function(colIndex){
var value=$(this).val();
// indexes need +1 to get the row number, because
// the indexes are 0-based.
if (undefined===columnValues[colIndex+1]){
columnValues[colIndex+1]=[];
}
if (undefined===rowValues[rowIndex+1]){
rowValues[rowIndex+1]=[];
}
rowValues[rowIndex+1].push(value);
columnValues[colIndex+1].push(value);
});
});
// send data to server
$.ajax({
url: 'ServletPost',
type: 'post',
data: {rows:rowValues, columns:columnValues},
dataType: 'json',
success: function(data){
// insert your server-calculated data to dom
var rows = data.rows,
columns = data.columns;
// insert your server-calculated data to dom
$("td.total").each(function(rowIndex){
$(this).text(rows[rowIndex+1]);
});
$("tr.totalCol td").each(function(columnIndex){
$(this).text(columns[columnIndex+1]);
});
}
});
});
先感謝您!
我不會告訴確切的解決方案,而是一種方法。
0>
$.ajax({
url:"ServletPost",
type:"POST",
dataType:'json',
data: {rows:rowValues, columns:columnValues},
success:function(data){
// codes....
}
});
1>在servlet的doPost()函數中
String[] rows= request.getParameterValues("rows[]");
String[] columns= request.getParameterValues("columns[]");
2>求和。
3>返回Json結果
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String jsonStr = "{\"rows\": \""+rowsResult+"\",\"columns\":\""+columnsResult+"\"}";
out.print(jsonStr);
out.flush();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.