<script type="text/javascript">
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('data-article-id');
else
articleorder += "," + $(this).attr('data-article-id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('/saveorder.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
?>
<li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
<?
}
?>
</ul>
<input type='button' value='Save order' onclick='saveOrder();'/>
请记住,我删除了所有的验证和检查。
<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}
?>
$('#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'
});
}
});
我觉得这个也能帮上忙。A)它被设计成在每次排序后发送回服务器时将有效载荷保持在最小值。(而不是每次发送所有的元素或者遍历许多服务器可能丢弃的元素) B)我需要在不损害元素的 id/名称的情况下发送回自定义 id。这段代码将从 asp.net 服务器获取列表,然后在排序之后只返回2个值: 已排序元素的 db id 和被删除元素旁边的 db id。基于这两个值,服务器可以很容易地确定新的位置。
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1"><a href="#pl-1">List 1</a></li>
<li plid="listId2"><a href="#pl-2">List 1</a></li>
<li plid="listId3"><a href="#pl-3">List 1</a></li>
<li plid="listId4"><a href="#pl-4">List 1</a></li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>