【问题标题】:jquery ui sortable serialize from childrenjquery ui 可排序从子级序列化
【发布时间】:2011-02-16 15:01:45
【问题描述】:

在对图像进行排序后,我想将包含图像路径和标题的数组发送到 PHP 脚本。 我可以对列表进行“序列化”或“toArray”,但是如何从 img 标签中获取属性?

<ul class="gallery">
    <li id="li-1">
        <img src="tn/001.jpg" alt="first caption" />
    </li>
    <li mycaption="some caption" id="li-2">
        <img src="tn/002.jpg" alt="second caption with éèçà international chars" />
    </li>
</ul>

$(".gallery").sortable({
    update : function() {
        serial = $('.gallery').sortable('serialize');
        alert(serial);
        /* $.ajax({
            url: "sort.php",
            type: "post",
            data: serial,
            error: function() {alert("theres an error with AJAX");}
        }); */
    }
});

【问题讨论】:

    标签: jquery-ui jquery-ui-sortable serialization children toarray


    【解决方案1】:

    下面是我如何将其序列化为具有两个成员 src_arrcaption_arr 的对象:

    var getPaths = function() {
        var imgPaths = { 'src_arr': [], 'caption_arr': []};
        $('.gallery img').each(function(){
            imgPaths.src_arr.push($(this).attr('src'));
            imgPaths.caption_arr.push($(this).attr('alt'));
        });
        return imgPaths;
    };
    

    所以我会用你的代码来做这个:

    $.ajax({
        url: "sort.php",
        type: "POST",
        dataType: 'html',
        data: getPaths(),
        success: function(data, textStatus, XMLHttpRequest) {
            // you need to do something in here
            $('#debug').html('<pre>' + data + '</pre>');
        },
        error: function() {
            alert("theres an error with AJAX");
        }
    });
    

    print_r() 中的 sort.php 的原始数据如下所示:

    Array
    (
        [src] => Array
            (
                [0] => tn/001.jpg
                [1] => tn/002.jpg
            )
    
        [caption] => Array
            (
                [0] => first caption
                [1] => second caption with éèçà international chars
            )
    
    )
    

    【讨论】:

    • 非常感谢!那么有没有必要使用序列化呢?昨晚我也在想同样的事情。如果您只是从数据库更新中发送一些 ID,这可能会很有用?
    • 请务必阅读jQuery.ajax 上的文档:api.jquery.com/jQuery.ajax - 它说“要发送到服务器的数据。如果还不是字符串,它会转换为查询字符串。它已附加到GET-requests 的url。请参阅processData 选项以防止这种自动处理。对象必须是键/值对。如果值是一个数组,jQuery 使用相同的键序列化多个值,即{foo:["bar1", "bar2"]} 变为'&amp;foo=bar1&amp;foo=bar2' 。”
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2011-02-11
    • 2010-12-29
    • 2019-09-30
    • 2011-01-11
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多