在烧瓶中处理Ajax请求 [英] Process Ajax request in flask
问题描述
我一直在学习烧瓶.我也已经在其中创建了两个项目.这是我的第三个项目.我总是坚持这一点.我想让服务器端代码在页面上发生事件时运行,例如单击一个按钮.
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.
在链接的图片中.我希望单击删除"按钮后将其删除.我已经将数据保存在mysql服务器上,所以我也希望从那里将其删除
这就是我所做的.我创建了一条路线"/delete_student",它可以删除学生. 但是问题是它总是重新加载页面,并且切换到不同的URL.我不希望任何事情发生.我该怎么办?我应该使用Ajax吗,如果可以,请告诉我,怎么办?
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 %}
烧瓶
@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'))
推荐答案
您应该使用javascript访问路由.
You should access the route with javascript.
使用jQuery检出AJAX:
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.form.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:
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());
}
});
});
这篇关于在烧瓶中处理Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!