【问题标题】:How to send data from jquery to flask如何将数据从 jquery 发送到烧瓶
【发布时间】:2017-06-01 19:26:25
【问题描述】:

我正在使用datatables 将数据呈现为分页表,如下所示。我添加了一个额外的功能,允许我在单击时从一行中获取一个值 (see this)

</head>
<body>
<div>
    <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
    </tbody>
</table>
</div>

<script type="text/javascript">
$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );
</script>
</body>
</html>

如何使用 Ajax 调用将 data[0] 中的这个值传递给烧瓶函数 process,这样我就不必刷新整个页面,即 process() 在完成时刷新指定的 DOM?我是新手,请多多包涵。

from flask import Flask, render_template, request

app = Flask(__name__)
app.debug=True

@app.route('/')
def index(name=None):
    return render_template('index.html', name=name)

@app.route('/process', methods=["GET", "POST"])
def process():
    #Do something with the value
    return render_template('process.html', value=value)

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

【问题讨论】:

  • 查看JQuery关于ajax的文档
  • 这很容易。只需使用$.post

标签: jquery python ajax flask datatables


【解决方案1】:

使用 flask_restful 创建一个 Flask API 服务器并从您的 jQuery 脚本接收一个 json 作为帖子。

下面应该让你明白我的意思:

from flask_restful import Resource, Api
from flask import Flask, request
import json

app = Flask(__name__)
api = Api(app)

class DataHandler(Resource):
  def get(self):
      return stuff

  def post(self):
    try:
      args = request.json
      # handle stuff
      return 200
    except:
      return 400

api.add_resource(DataHandler, '/endpoint_name')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2019-06-06
    • 2023-03-11
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多