【问题标题】:jQuery UI Sortable - saving order when button clickedjQuery UI Sortable - 单击按钮时保存顺序
【发布时间】:2015-02-04 10:44:29
【问题描述】:

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

我试图用一个点击事件来包围 ajax 调用,但是根据用户的可排序操作的计数,将会完成几个 POST 请求。我只需要一个 ajax 发布请求。

$(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>

【问题讨论】:

    标签: jquery ajax jquery-ui serialization


    【解决方案1】:

    有一个内置的方法可以做到这一点。参考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);
        });
    });
    

    【讨论】:

    • 对我来说,这段代码不会只发送一个 ajax 调用,而是根据单击时可排序操作的计数发送 ajax 调用数
    • @Rsganesh 检查您是否多次绑定事件。
    【解决方案2】:
    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'
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多