我正在使用 jQuery 库来生成一个有序列表,该列表能够通过拖放对项目进行重新排序。我想将订单信息发送到数据库,下次您刷新页面(或将其加载到另一个浏览器/计算机上)时,它就会有您的订单。
我在 mySQL 中为列表的每个元素创建了一个表,现在我正在按 creation_date
进行排序。那么什么是最好的解决方案以及我在哪里(以及如何)保存订单?
最佳答案
这是我想到的解决方案。它未经测试,但应该为您指明正确的方向。在要排序的表中有一个 INT 'order' 列。
HTML/javascript (jquery-ui)
<!-- This is the list of items where the item's data base id is in the element
id, i.e. id="item-DATABASE_ID". These items can be displayed with PHP by
SELECTing them from the database using ORDER BY order ASC -->
<ul id="sortable">
<li id="item-1">Foo</li>
<li id="item-2">Bar</li>
<li id="item-3">Baz</li>
</ul>
<script type="text/javascript">
$(function() {
// This turns the list into a jquery UI sortable list
$("#sortable").sortable({
// This even fires whenever the list is changed
change: function(event, ui) {
// This sends the list data to an AJAX handler
$.post({
url: 'path_to_ajax_handler.php',
// The serialize function transforms the list information
// into a query string i.e.: item[]=1&item[]=2&item[]=3
data: $('#sortable').sortable("serialize")
});
}
});
});
</script>
PHP
<?php
// The IDs of the items to be sorted are passed to the AJAX handler in the order
// they are listed in the page
if (isset($_POST['item']))
{
$items = (array)$_POST['item'];
// This updates all the items in the table with the correct order
for ($x = 0; $x < count($items); $x++)
{
$query = "UPDATE * FROM orderable_things SET order = $x WHERE id = ".$items[$x];
mysql_query($query);
}
}
关于php - 保存列表的顺序 (php/zend/jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/832539/