在烧瓶中处理Ajax请求

时间:2018-02-03 07:33:09

标签: flask flask-sqlalchemy

我一直在学习烧瓶。我还在其中创建了两个项目。这是我的第三个项目。我总是坚持这一点。我希望在页面上发生事件时运行服务器端代码,例如单击一个按钮。

In the linked image. I want the entry be deleted when 'delete' button is clicked. I've holding the data on mysql server, so I want it to be deleted from there as well

这就是我所做的。我创建了一条路线' / delete_student'并处理删除学生的问题。 但问题是它总是重新加载页面,它也切换到不同的URL。我不希望任何一件事发生。我该怎么办?我应该使用Ajax,如果是,请告诉我,怎么做?

HTML

{% for i in data %}
            <tr>
                <td>{{i['roll_no']}}</td>
                <td>{{i['name']}}</td>
                <td>{{i['username']}}</td>
                <td>{{i['password']}}</td>
                <td><a href="#">Edit</a></td>
                <td><a href="{{url_for('delete_student')}}">Delete</a></td>
            </tr>
{% endfor %}

烧瓶

@app.route('/delete_student')
@is_logged_in
def delete_student():
if session['username']=='nitti':
    cur = mysql.connection.cursor()
    #pop the row from the table?
    #how to identify the row being deleted?
    return render_template(url_for('student_summary'))

1 个答案:

答案 0 :(得分:1)

您应该使用javascript访问该路线。

使用jQuery检出AJAX:

http://flask.pocoo.org/docs/0.12/patterns/jquery/

例如,如果您有一个显示“删除学生”的按钮:

@app.route("/_delete_student")
def delete_student():
    student_id = request.args.get("student_id")
    cur = mysql.connection.cursor()
    cur.execute("DELETE FROM students WHERE student_id = %s", (student_id,)
    conn.commit()
    return jsonify(status="success")

JavaScript的:

$("#delete_student").click(function(){
    $.ajax({
      type: 'POST',
      url: "/_delete_student",
      data: {student_id: 1},
      dataType: "text",
      success: function(data){
                 alert("Deleted Student ID "+ student_id.toString());
               }
    });
});