2012-01-12 113 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