更新时间:2023-02-23 12:54:07
返回render_template
无效,因为数据是通过Ajax发送的.它将返回模板内容. done
方法接收Flask返回的数据.我要添加一个示例代码来演示如何处理带有JSON数据的Ajax提交.
app.py
:
Flask,render_template,request,jsonifyapp = Flask(__ name__)@ app.route('/process',methods = ["GET","POST"])def process():如果request.method =='POST':数据= request.json返回jsonify(data)返回render_template("form.html")app.run(debug = True)
form.html
:
< html>< head>< title>表格</title>< script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head><身体>< div id ="data"></div><输入type ="text" id ="textField"/>< button id ="demo_btn">虚拟按钮</button>< script>$(document).ready(function(){$(#demo_btn").on("click",function(){var text = $('#textField').val();var obj = {name:text};var myJSON = JSON.stringify(obj);$ .ajax({网址:"/process",类型:"post",contentType:"application/json",dataType:'json',数据:myJSON}).done(function(result){$(#data").html(result ["name"]);}).fail(函数(jqXHR,textStatus,errorThrown){console.log("fail:",textStatus,errorThrown);});});});</script></body></html>
输出:
参考:
http://api.jquery.com/jquery.ajax/ >
i want to send JSON format data in my flask app using AJAX call, when i send it i got "None" in flask.
here is jquery,
$('#form').on('click',function(){
var text = $('#textField').val();
var obj = {name:text};
var myJSON = JSON.stringify(obj);
$.ajax({
data : myJSON,
url: '/process',
type : 'post',
contentType: 'application/json',
dataType : 'json'
})
})
here is my Flask route,
@app.route('/process',methods=["POST"])
def process():
data = request.json
return render_template("form.html",data = data)
in data i got "None".
return render_template
is not fruitful as data is being sent via Ajax. It will return the template contents.done
method in Ajax.I am adding an example code to demonstrate how to handle Ajax submission with JSON data.
app.py
:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/process',methods=["GET", "POST"])
def process():
if request.method == 'POST':
data = request.json
return jsonify(data)
return render_template("form.html")
app.run(debug=True)
form.html
:
<html>
<head>
<title>Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="data"></div>
<input type="text" id="textField" />
<button id="demo_btn">Dummy button</button>
<script>
$(document).ready(function () {
$("#demo_btn").on("click", function() {
var text = $('#textField').val();
var obj = {name:text};
var myJSON = JSON.stringify(obj);
$.ajax({
url: '/process',
type : 'post',
contentType: 'application/json',
dataType : 'json',
data : myJSON
}).done(function(result) {
$("#data").html(result["name"]);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("fail: ",textStatus, errorThrown);
});
});
});
</script>
</body>
</html>
Output:
Reference: