多维数组传递给Ajax可排序jQuery



我使用可排序的jQuery ui函数。有了这个

$(".draggable-right").sortable({
connectWith: ".connected-sortable",

update: function(event, ui) {
var ordine_video = $(this).sortable('toArray', {
attribute: 'data-id'
});

// POST to server using $.post or $.ajax
$.ajax({
data: {
'ordine_video': ordine_video,
},
type: 'post',
dataType: 'json',
url: 'save_playlist.php'
});
//     alert(idsInOrder);
console.log(ordine_video);
},

}).disableSelection();

我可以将数组中具有attribute:data-id值的数组作为传递

["BMPR-00026.mp4", "BMPR-00026.mp4"]

如果我想传递这样一个带有密钥和值的数组

{"BMPR-00026.mp4":"value_1", "BMPR-00026.mp4": "value_2"}

怎么办?我在领域

<li class="ui-sortable-handle" data-id="BMPR-00026.mp4" style="" rel="value_1">element</li>
<li class="ui-sortable-handle" data-id="BMPR-00026.mp4" style="" rel="value_2">element</li>

考虑以下内容。

function serializeList(list) {
var results = {};
$("li", list).each(function(i, el) {
results[$(el).attr("data-id")] = $(el).attr("rel");
});
return results;
}
$(".draggable-right").sortable({
connectWith: ".connected-sortable",
update: function(event, ui) {
var ordine_video = serializeList(this);
$.ajax({
data: {
'ordine_video': ordine_video,
},
type: 'post',
dataType: 'json',
url: 'save_playlist.php'
});
console.log(ordine_video);
}
}).disableSelection();

这将创建一个函数,您可以将列表传递给它,它将迭代每个列表项来构建一个对象。

需要注意的是,每个data-id必须是唯一的。像这样:

{
"BMPR-00026.mp4": "value_1",
"BMPR-00027.mp4": "value_2"
}

如果它们相同,则将更新该索引的值,而不是添加新条目。

最新更新