问题描述
我想使用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,然后将订单写入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!