jQuery基于返回的数组更新多个div

时间:2013-09-15 15:57:11

标签: jquery jquery-ui-sortable

我被jQuery / ajax打败了。

我正在尝试使用jQuery可排序的php脚本中的值计算页面上的多个表行。

我可以轻松更新一行。不确定如何将ajax脚本中的结果添加到数组中并将其发回,然后排序并更新行。

这是我的javascript:

<script>
$(function() {                                                           
    $( "#sort tbody" ).sortable({ 
        update : function () { 
            var order = $('#sort tbody').sortable('serialize'); 
            $("#subtotal").load("ajax_update_line_order.php?"+order); 
        },
        placeholder: "ui-state-highlight" 
    }); 
    $( "#sort tbody" ).disableSelection();
});
</script>

html是一个简单的表格。我可以给每个人一个唯一的ID或类(不确定哪个),例如row0,row1,row2等,对应于该位置的数字。

这是我的ajax_update_line_order.php:

<?php
........ 

foreach ($_GET['listItem'] as $position => $item)
{
   //Update position in mysql DB here (all ok)

   //Calculations here (all ok)

   //Add calculated result and position to an array
   $array[] = $calculation; (the array key will match the position here, so guess I can use this to reference when updating the table rows)

}

print_r($array); //Not sure how to get this array back to read and update the page
exit();
?>

非常感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

首先,通过JSON编码返回数组,而不是print_r。后者用于var转储,即调试,而不是编程操作。

exit(json_encode($array));

然后在你的JS中,你需要在AJAX请求上成功回调,它将被传递(自动)解析的JSON,即从PHP数组开始的。然后我们迭代该数组,并为其中的每个项输出一行。

var tbody = $('#sort tbody')
$("#subtotal").load("ajax_update_line_order.php?"+order).done(function(data) {
    for (var i=0, len = data.length; i<len; i++) {
        var row = $('<tr />');
        /* then append some TDs to the row */
        tbody.append(tr);
    }
});

如果您是done()的新手,请阅读jQuery延迟对象(其中一个例子是AJAX请求)。