Process Ajax request in flask

风格不统一 提交于 2019-12-13 10:17:12

问题


I've been learning flask. i've also created two projects in it. It's my third project. I'm always stuck on this point. I want to make server side code run when a event happens on page say, a button is clicked.

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

Here is what I have done. I created a route '/delete_student' and it handles deleting the student. But the problem is it's always reloading the page and also It switches to different url. I don't want any of them to happen. What should I do? Should I use Ajax, if yes, please tell me, how?

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 %}

Flask

@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:


You should access the route with javascript.

Checkout AJAX with jQuery:

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

For example, if you have a button that says "Delete Student":

@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());
               }
    });
});


来源:https://stackoverflow.com/questions/48595068/process-ajax-request-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!