2012-01-12 115 views
1

我有一个包含项目列表的数据库表。相关字段是“项目名称”和“list_order”。使用JQuery UI重新排序数据库字段可排序

我希望能够通过触发ajax调用每次物品排序时重新排序表中的“list_order”列。

举例来说,如果我有以下数据

Milk  1 
Cookies 2 
Cereal 3 

我想使用jQuery UI拖动谷物到列表的顶部,有这反映在数据库中

Milk  2 
Cookies 3 
Cereal 1 

任何人都可以指向我的例子或链接,或提供解释如何做到这一点? TIA。

回答

2

你应该能够使一个AJAX调用PHP脚本与list_position => ITEM_ID的数组,然后在PHP中遍历所述阵列和

update table set list_position='$key' where id='$val'; 

,然后你当然会被list_position排序在选择有关未来查询的数据时。

编辑:刚刚发现这个例子在线@http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/

JS:

<script type="text/javascript"> 
// When the document is ready set up our sortable with it's inherant function(s) 
$(document).ready(function() { 
    $("#test-list").sortable({ 
    handle : '.handle', 
    update : function() { 
     var order = $('#test-list').sortable('serialize'); 
     $("#info").load("process-sortable.php?"+order); 
    } 
    }); 
}); 
</script> 

HTML:

<pre> 
    <div id="info">Waiting for update</div> 
</pre> 
<ul id="test-list"> 
    <li id="listItem_1"> 
    <img src="arrow.png" alt="move" width="16" height="16" class="handle" /> 
    <strong>Item 1 </strong>with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a> 
    </li> 
    <li id="listItem_2"> 
    <img src="arrow.png" alt="move" width="16" height="16" class="handle" /> 
    <strong>Item 2</strong> 
    </li> 
    <li id="listItem_3"> 
    <img src="arrow.png" alt="move" width="16" height="16" class="handle" /> 
    <strong>Item 3</strong> 
    </li> 
    <li id="listItem_4"> 
    <img src="arrow.png" alt="move" width="16" height="16" class="handle" /> 
    <strong>Item 4</strong> 
    </li> 
</ul> 
<form action="process-sortable.php" method="post" name="sortables"> 
    <input type="hidden" name="test-log" id="test-log" /> 
</form> 

PHP:

<?php 
/* This is where you would inject your sql into the database 
but we're just going to format it and send it back 
*/ 
foreach ($_GET['listItem'] as $position => $item) : 
    $sql[] = "UPDATE `table` SET `position` = $position WHERE `id` = $item"; 
endforeach; 
print_r ($sql); 
?> 
+1

你可以做的更新中单一的更新像'u pdate ... set position = case id when ... end where(in)(...)',基本上使用CASE作为关联数组的SQL版本。 – 2012-01-12 23:35:32

+0

我遇到了一个问题,即正在更新的案例数量达到几百个,使用'CASE WHEN THEN'方法生成的查询速度很慢。 – 2013-08-28 08:59:39

+0

是否可以仅为受影响的行发送SQL UPDATE?所以如果'listItem_2'和'listItem_3'被交换,它应该只更新这两个并且保留1和4? (为了最小化服务器资源,例如当只需要更新时需要一次更新数百行) – Jon 2017-02-23 21:43:06