使用HTML5sortable序列化AJAX的数据 [英] Serialize data for AJAX using HTML5sortable

查看:211
本文介绍了使用HTML5sortable序列化AJAX的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为jQuery使用整洁的排序插件,HTML5 Sortable http://farhadi.ir/projects/html5sortable/,但是还没有找到一种理想的方式来序列化数据以作为AJAX POST请求发送(以更新数据库).

I'm using a neat sort plugin for jQuery, HTML5 Sortable http://farhadi.ir/projects/html5sortable/ but haven't found an ideal way of serialize data to send as an AJAX POST request (to update DB).

HTML

<ul class="sortable">
    <li data-id="1">One</li>
    <li data-id="2">Two</li>
    <li data-id="3">Three</li>
    <li data-id="4">Four</li>
    <li data-id="5">Five</li>
</ul>

jQuery

$('ul.sortable').sortable().bind('sortupdate', function() 
{
   var data = ??;  // serialize all data-id's ... this is my problem

   $.post('/sortupdate.php',data,function(){ // PHP script sets new order in DB
       alert('updated');
   });
});

所以我想发生的事情是,当我将LI项目拖动到新位置时,sortupdate事件应触发该函数并发送新的data-id属性值顺序.我当前的想法是遍历LI,并将属性值添加到数组中.有没有更聪明的方法可以执行此操作?或者,最有效的循环方法是什么? (我主要是一个知道后端的人).谢谢!

So what I want to happen is that when I drag an LI item to a new position then the sortupdate event should trigger the function and send the new order of data-id attribute values. My current idea is to loop through the LI's and add attribute values to an array. Is there any smarter way of doing this, or, what is the most efficient way of doing the loop? (I'm mostly a backend guy you know). Thanks!

推荐答案

由于该插件没有内置的序列化方法,因此您必须手动执行此操作.

Since the plugin doesn't come with a built-in serialize method, you have to do it manually.

var dataIDList = $('ul.sortable li').map(function(){ 
    return $(this).data("id");
}).get().join(",");

(本质上就是您在最后描述的内容,它循环遍历并创建一个列表.)

现在您可以将其发布为列表:

Now you can post it as a list:

$.post(url,{ idlist: dataIDList }, completeandler);

您也可以将其发布为数组,只需删除.join(",");

You could also post it as an array, just remove .join(",");

这篇关于使用HTML5sortable序列化AJAX的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆