本文介绍了jQuery ui sortable - 使用Python / Flask / SQLite保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个拖放效果,只是找到jQuery sortable最可行和最简单的解决方案,但我想在重新排序后保存位置。使用php / sqlite我可以这样做,但因为我使用框架烧瓶解决方案必须在python中。我来这里搜索这段代码

i need a drag and drop effect, just finding the jQuery sortable the most viable and easy solution, but I would like to save the positions after reordered. Using php/sqlite i can do this but as I am using the framework flask the solution would have to be in python. I came to this code searching here

html:

$(function() {
    var $sortables = $("#sortMe").sortable({
        stop: function() {
            var sortedItems = $sortables.sortable("toArray");
        }
    });
});

py:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

class Sortable(db.Model):
    __tablename__ = 'sortables'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    data = db.Column(db.String)

    def __init__(self, data):
        self.data = data

@app.route("/saveorder", methods=['GET', 'POST'])
def save_order():
    if request.method == "POST":

edit。

现在,我得到了这个

html:

    $(function() {
        $('#sortMe').sortable({
            update: function(event, ui) {
                var postData = $(this).sortable('serialize');
                console.log(postData);

                $.ajax({
                    url: '/saveorder',
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({list: postData}),
                    success: function (ret) {
                        alert('JSON posted: ' + JSON.stringify(ret));
                    }
                });
            }
        });
    });

py:

@app.route("/saveorder", methods=['GET', 'POST'])
def saveorder():
    json = request.json
    print(json)

    return jsonify(json)


推荐答案

我找到了解决方案

app.py

from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


class Sortable(db.Model):
    __tablename__ = 'sortables'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    data = db.Column(db.String)

    def __init__(self, data):
        self.data = data


db.create_all()


@app.route('/')
def index():
    sort = Sortable.query.filter_by(id=1).first()
    ordem = str(sort.data)
    return render_template('index.html', sort=sort, ordem=ordem)


@app.route('/post', methods=['GET', 'POST'])
def post():
    json = request.json
    x = json.replace('item[]=', ',')
    y = x.replace('&,', '')
    final = y.replace(',', '')

    sort = Sortable.query.filter_by(id=1).first()
    sort.data = final

    db.session.commit()

    return jsonify(final)


if __name__ == '__main__':
    app.run(debug=True)

index.html

index.html

<html>
  <head>
    <title>Flask example</title>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function(){
            $('#sortMe').sortable({
                update: function(event, ui) {
                    var postData = $(this).sortable('serialize');

                    $.ajax({
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        dataType: 'json',
                        url: '/post'
                    });
                }
            });
        });
    </script>
  </head>
  <body>
    <ul id="sortMe">
    {% for i in ordem %}
        <li id="item_{{ i }}">item {{ i }}</li>
    {% endfor %}
    </ul>
  </body>
</html>

这篇关于jQuery ui sortable - 使用Python / Flask / SQLite保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:05