jQuery UI sortable - sorting images

后端 未结 2 1702
感情败类
感情败类 2021-02-06 18:55

I\'ve just implemented the jQuery UI sortable plugin for a set of images. The markup I have is as follows:

2条回答
  •  你的背包
    2021-02-06 19:23

    Basically, do this:

    First, change your items' id format to the underscored format expected by sortable:

  • Then, use sortable's serialize method in its stop event:

    ... // Within your sortable() setup, add the stop event handler:
    stop:function(event, ui) {
      $.ajax({
        type: "POST",
        url: path/to/your/ajax/reorder.php,
        data: $("#images").sortable("serialize")
      });
    }
    ...
    

    When you use $("#images").sortable("serialize"), sortable's serialize method will go through the children of #images, i.e. all your li elements, and turn all the ids it finds (image_7884029, image_7379458, etc.) into a list of items like image[]=7884029&image[]=7379458..., in the order they now appear in the list, after sorting (because you're calling it from stop()). Basically it works similar to how an array of checkboxes gets sent when posting a form.

    You can then pick this up in your server-side "reorder.php", to assign new values to your sort_order column:

    $items = $_POST['image'];
    if ($items) {
      foreach($items as $key => $value) {           
        // Use whatever SQL interface you're using to do
        // something like this:
        // UPDATE image_table SET sort_order = $key WHERE image_id = $value
      } 
    } else {
      // show_error('No items provided for reordering.');
    }
    

    And you're done.

提交回复
热议问题