Jquery可排序和可拖动 - 用Ajax结果替换拖动的内容

时间:2016-03-24 07:13:55

标签: jquery-ui jquery-ui-draggable

这可能是一个简单的问题,但是如何用ajax调用替换我用html拖动的东西?

所以,如果可拖动的项目只是'文本'项目(如下面的html代码段),当我拖动我通过帮助方法使用'图像'的东西时,我怎么能'放弃'不使用其中任何一个,但插入从ajax调用返回的html。

我在哪里拨打电话(顺便说一下,使用'input-type'值来调用ajax来获取正确的html)?

如何防止插入默认的“拖动项目”?即我不希望div放入或辅助方法图像....

我是否需要像droppable一样添加,或者像sortable事件那样在received进行添加(工作方式,无法从帮助方法中移除图片) )??? (我一直在尝试这两种方式,虽然ajax调用有效但我得到了数据等,因为我不知道如何防止丢弃默认的东西我不确定'我用'结果'取代'什么'来自电话......)

$("#desktoplayout").sortable({
    receive: function (event, ui) {
        $(this).append('<div>html from ajax call</div>'); // kind of works... but the image from the 'helper method' on the 'draggable' is still there.
    }
});   // A sortable list of stuff into which things are dragged.

var input-type;

$("#draggableItems .item").draggable({
    connectToSortable: "#desktoplayout",
    helper: function (event) {
        return "<div class='item'><img src='/Images/Header.png' /></div>";
    },
    start: function (event, ui) {
        input-type = $(this).find('.preview').data("input-type");
    },
    drag: function(e, t) {
    },
    stop: function(e, t) {
    }
});

<div id="draggableItems">
    <div class="item">
        <div class="preview" data-input-type="1">
            TEXT
        </div>
    </div>
</div>

更新

这似乎做了我想要的......在remove上调用helper正确的方法吗?

receive: function(event, ui) {
    ui.helper.remove();
    var $this = $(this);
    $.get("somewhere", function(data) {
        // Note: presume more logic here.....
        $($this).append(data);
    });
}

1 个答案:

答案 0 :(得分:1)

以下是一个解决方案的工作示例:

https://jsfiddle.net/Twisty/zh9szubf/

<强> HTML

<div id="draggableItems">
  <div class="item">
    <div class="preview" data-input-type="1">
      TEXT
    </div>
  </div>
</div>

<ul id="desktoplayout">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

<强> JQuery的

$(function() {
  $("#desktoplayout").sortable({
    receive: function(event, ui) {
      var newItem;
      $.post("/echo/html/", {
        html: "<li class='newItem'>From Ajax</li>"
      }, function(data) {
        ui.helper.replaceWith(data);
      });
    }
  });

  var inputType;

  $("#draggableItems .item").draggable({
    connectToSortable: "#desktoplayout",
    helper: function (event) {
      return "<div class='item'><img src='/Images/Header.png' /></div>";
    },
    start: function(event, ui) {
      inputType = ui.helper.find('.preview').data("input-type");
    }
  });
});

这也适用于$.get(),但例如,它必须是$.post()。基本上,无论您想要什么,最重要的是结果,该代码应该在ui.helper.replaceWith()部分。