我有一个包含输入文本的表,用于计算JQuery中的行总数和coumns的总和。
可以将AJAX帖子中的表发送给PHP并在那里进行行和列的计算吗?
这是我的表:
<table id="sum_table">
<tr>
<td><input value="0" class="sum1" /></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr class ="totalCol">
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<button id="tabla">+</button>
<button id="moes">Hide/Show</button>
这是我如何对列进行求和:
//Mostramos y ocultamos la tabla
$("#moes").click(function(){
$("table").toggle();
});
//Sumamos las columnas
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
提前谢谢你:)
答案 0 :(得分:3)
$(document).ready(function() {
$('#tabla').click(function() {
var col1 = [];
var col2 = [];
var col3 = [];
// collect all data from table col1
$.each($('table td input.sum1'), function(k, v){
col1.push($(v).val());
});
// collect all data from table col2
$.each($('table td input.sum2'), function(k, v){
col2.push($(v).val());
});
// collect all data from table col3
$.each($('table td input.sum3'), function(k, v){
col3.push($(v).val());
});
// send data to server
$.ajax({
url: 'calc.php',
type: 'post',
data: {'col1': col1, 'col2': col2, 'col3': col3,},
dataType: 'json',
success: function(data){
// insert your server-calculated data to dom
$('.totalCol td:nth-child(1)').text(data.SumCol1);
$('.totalCol td:nth-child(2)').text(data.SumCol2);
$('.totalCol td:nth-child(3)').text(data.SumCol3);
}
});
});
});
您可以在服务器上总结您的帖子,例如: calc.php
:
$SumCol1 = _sumUp($_POST['col1']);
$SumCol2 = _sumUp($_POST['col2']);
$SumCol3 = _sumUp($_POST['col3']);
echo json_encode(array(
"SumCol1" => $SumCol1,
"SumCol2" => $SumCol2,
"SumCol3" => $SumCol3
));
function _sumUp($data)
{
$sum = 0;
foreach($data as $k => $v)
{
$sum += $v;
}
return $sum;
}
注意:未经测试。只有基本结构。