如何将数据从jquery发送到烧瓶

时间:2017-06-01 19:26:25

标签: jquery python ajax flask datatables

我使用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]中的此值传递给flask函数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()

1 个答案:

答案 0 :(得分:0)

使用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')