问题描述
我想使用 jQuery UI sortable
函数来允许用户设置订单,然后在更改时将其写入数据库并更新它.有人可以写一个例子来说明如何做到这一点吗?
I want to use the jQuery UI sortable
function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?
推荐答案
jQuery UI sortable
功能包括一个 serialize
方法去做这个.这很简单,真的.这是一个简单的示例,该示例在元素更改位置后立即将数据发送到指定的 URL.
The jQuery UI sortable
feature includes a serialize
method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
它的作用是使用元素 id
创建一个元素数组.所以,我通常会做这样的事情:
What this does is that it creates an array of the elements using the elements id
. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
当你使用 serialize
选项时,它会创建一个像这样的 POST 查询字符串:item[]=1&item[]=2
等等.所以如果你例如,在 id
属性中使用您的数据库 ID,然后您可以简单地遍历 POSTed 数组并相应地更新元素的位置.
When you use the serialize
option, it will create a POST query string like this: item[]=1&item[]=2
etc. So if you make use - for example - your database IDs in the id
attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
例如在 PHP 中:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
这篇关于jQuery UI Sortable,然后将订单写入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!