JQuery UI保存可排序列表

我知道之前已经问过这个问题,但解决方案对我不起作用。 我正在尝试将新的项目顺序保存到数据库中。

我已经非常简化了它,但这是它的基本思想。 我有一个嵌入了可排序列表的表单。

  • Item
  • Item
  • Item
  • Item

我有JQuery和JQuery UI Loaded,以下代码启用了可排序列表function,并将项目ID和新排序顺序发布到php脚本。 “editor”变量是一个在加载时设置的公共变量,它工作正常。 排序工作正常,但是当我重新排序列表时,发布的新订单值似乎没有改变。

 //sorting feature $("#itemsort").live('hover', function() { $("#itemsort").sortable({ opacity:.5, update : function () { var neworder = $('#itemsort').sortable('serialize'); var inputs = serializePost('#itemlist'); $.post("core/actions.php",{ 'order': editor, 'inputs': inputs, 'neworder': neworder},function(){ alert("Order saved.", 1); }); } }); }); 

在actions.php上……

  if(isset($_POST['order'])){ //set a variable for each post $batchid = $_POST['inputs']['itemid']; parse_str($_POST['neworder'], $neworder); //count the number of entries to be ordered $count = count($batchid); //use the count to create an incremental loop for each item to be updated. $i=0; while ($i <= $count) { $query ="UPDATE {$_POST['order']} SET order=$neworder[item][$i] WHERE id=$batchid[$i]"; ++$i; } } 

我不确定为什么每个项目的订单都不会改变。

有任何想法吗?

-L

 $("#list").live('hover', function() { $("#list").sortable({ update : function () { var neworder = new Array(); $('#list li').each(function() { //get the id var id = $(this).attr("id"); //create an object var obj = {}; //insert the id into the object obj[] = id; //push the object into the array neworder.push(obj); }); $.post("pagewhereyouuselist.php",{'neworder': neworder},function(data){}); } }); }); 

然后在您的PHP文件中,或在此示例中“pagewhereyouuselist.php”

 $neworderarray = $_POST['neworder']; //loop through the list of ids and update your db foreach($neworderarray as $order=>$id){ //you prob jave a connection already i just added this as an example $con = mysql_connect("host","username","password"); if (!$con){ die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("UPDATE table SET order = {$order} WHERE id = {$id}"); mysql_close($con); } 

应该这样做我没有测试它,因为它是一个示例连接。 我实际使用的实际脚本更具体到我的程序这是一个简化版本来显示概念

试试这个:

您的HTML字段

 
  • Item 1
  • Item 2
  • Item 3
  • Item 4

JS发送订单:

 $("#itemsort").live( 'hover', function() { $("#itemsort").sortable({ update: function () { var inputs = $('#itemlist').serialize(); $.post("./jq-ui-test.php", inputs, alert("Order saved.") ); } }); }); 

保存订单:

 if( isset( $_POST['itemid'] ) && is_array( $_POST['itemid'] ) ) { foreach( $_POST['itemid'] as $order => $item ) { $order = intval( $order ); $item_esc = mysql_real_escape_string( $item ); $sql_query = "UPDATE {$_POST['order']} SET order={$order} WHERE id = '{$item_esc}'"; } } 

此外,如果您希望启动顺序从1开始(而不是从0开始),请更改$order = intval( $order ); to $order = intval( $order ) + 1;