【发布时间】:2018-11-25 17:27:21
【问题描述】:
我正在尝试在可排序更新时通过 ajax 重新排序列表,但是在页面加载时已初始化可排序之后通过 ajax 将新项目添加到此列表后,它无法识别带有“序列化”的新项目“ 功能。它确实允许我拖动它,就好像它正在工作一样,但是使用我的更新函数发送的代码缺少新元素。
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
$.post('admin/ereg_forms/set_category_position', serialized, function(data) {
if (data.status == 'error') {
alert(data.message);
}
});
}
});
//Add category submit
$("#add-category-submit").click(function(e) {
e.preventDefault();
$(".errors-block").html('');
$('#add-category-submit').hide();
$.ajax({
url: $("#add-category-form").attr('action'),
type: 'POST',
data: $('#add-category-form').serialize(),
dataType: 'json',
success: function(data) {
$('#add-category-submit').show();
//Check if server side validation passed
if (data.status == 'error') {
//Show error on popup dialog
$("#add-category-form .errors-block").html(data.message);
alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
} else {
var category_data = data.data;
var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>'
$(tableRow).appendTo('#categories-list tbody');
resetForm($('#add-category-form'));
//Close popup window
$('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}
},
error: function(data) {
alert('An unknown error has occurred, please try again.');
$('#add-category-submit').show();
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
我到处寻找解决方案,但没有找到有效的解决方案。我曾尝试将“刷新”函数与 sortable 一起使用,我尝试在 ajax 调用的成功函数中初始化 sortable 以添加新类别,但它也不起作用。
当我 console.log(serialized) 时,它只有数组中最初加载的元素。
【问题讨论】:
-
$( "#add-category-submit" )在您发布的代码中不存在。 -
您使用的是什么“可排序”?请修改以显示一个工作示例。
-
我为可排序进行了编辑,做出了广泛的假设。
-
@MarkSchultheiss 我添加了 add-category-submit 功能并更新了jQuery版本,您添加的jQueryUI版本是正确的。这基本上与我在我的网站上的内容完全相同,只是我删除了一些列以使其成为一个更简单的示例。
标签: javascript jquery ajax