0

jQuery/ajax にやられています。

jQuery sortableを使用して呼び出されたphpスクリプトで計算された値で、ページ上の複数のテーブル行を更新しようとしています。

1行を簡単に更新できます。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();
?>

どんな助けでも大歓迎です。

前もって感謝します。

4

1 に答える 1

1

print_rまず、 'ingではなく、JSON エンコードして配列を返します。後者は、プログラムによる操作ではなく、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 要求はその一例です) について読んでください。

于 2013-09-15T16:06:51.507 に答える