jQuery UI Sortable - 单击按钮时保存顺序

时间:2015-02-04 10:44:29

标签: jquery ajax jquery-ui serialization

我有一个列表,其中的项目应由用户使用jQuery UI Sortable进行排序。在用户选择了他的最终订单后,他必须单击一个按钮" Ready"。单击按钮后,应使用serialize和Ajax将订单发送到saveoder.php。

我试图用click事件包围ajax调用,但是根据用户的可排序操作的数量,会有几个POST请求完成。我只需要一个ajax post请求。



$(function() {	
	$( "#sortable" ).sortable({
		update: function(event, ui) {		
			var order = $(this).sortable('serialize');
			
			$(document).on("click", "button" , function() { //that doesn't work
				$.ajax({
					data: order,
					type: 'POST',
					url: 'saverank.php'
				});
			});
		}
	}).disableSelection();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<ul id="sortable">
  <li id="id_1">Item 1</li>
  <li id="id_2">Item 2</li>
  <li id="id_3">Item 3</li>
</ul>
<button>Ready</button>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:7)

有一种内置方法可以做到这一点。请参阅serializetoArray

演示:http://jsfiddle.net/lotusgodkk/GCu2D/539/

JS:

$(function () {
    $("#sortable").sortable({
        update: function (event, ui) {
            var order = $(this).sortable('serialize');

            $(document).on("click", "button", function () { //that doesn't work
                $.ajax({
                    data: order,
                    type: 'POST',
                    url: 'saverank.php'
                });
            });
        }
    }).disableSelection();
    $('button').on('click', function () {
        var r = $("#sortable").sortable("toArray");
        var a = $("#sortable").sortable("serialize", {
            attribute: "id"
        });
        console.log(r, a);
    });
});

答案 1 :(得分:0)

For single ajax call. Modified from accepted answer

$(function () {
    $("#sortable").sortable({
        update: function (event, ui) {
            var order = $(this).sortable('serialize');
        }
    }).disableSelection();
    $('button').on('click', function () {
        var a = $("#sortable").sortable("serialize", {
            attribute: "id"
        });
        console.log(a);
        $.ajax({
            data: a,
            type: 'POST',
            url: 'saverank.php'
        });
    });
});