我刚刚解决了完全相同的问题。我将撕毁我的处理方式。
对于客户端,我使用了this 库。
Javascript:
$( document ).ready(function() {
$("#table-categories").rowSorter({
onDrop: function(tbody, row, new_index, old_index) {
$.post("/path/to/api/priority", {old_index: old_index + 1, new_index: new_index + 1, _token: "<?php echo csrf_token(); ?>" }, function(result){
console.log('server result: ' + result);
});
},
});
});
注意 old_index 和 new_index 上的 +1,因为我没有覆盖 rowsorter 库上的行索引,但我的模型上的 priority 索引从 1 开始,而不是 0。如果你从 0 开始,只需按原样发送索引即可。
服务器端(Laravel 控制器):
public function priority()
{
$old = \Input::get('old_index');
$new = \Input::get('new_index');
foreach (\App\Category::all() as $category)
{
if ($category->priority == $old)
{
$category->priority = $new;
$category->save();
}
else
{
if ($old < $new)
{
if ($category->priority <= $new AND $category->priority >= $old)
{
$category->priority -= 1;
$category->save();
}
}
else
{
if ($category->priority <= $old AND $category->priority >= $new)
{
$category->priority += 1;
$category->save();
}
}
}
}
return 'OK';
}
注意:此逻辑唯一缺少的实现是处理从表中插入或删除行时的优先级,请记住实现它们。如果您在执行此操作时遇到问题,请告诉我,以便我添加实现。