[英]How can I pass JSON of flask to Javascript
我有一个索引页,其中包含一个表单,填写表单并将数据发送到URL,URL捕获输入,并在数据库中进行搜索,返回JSON。 如何获取此JSON,并使用Javascript将其放在另一个HTML页面上?
索引形式:
<form action="{{ url_for('returnOne') }}", method="GET">
<p>Nome: <input type="text" name="nome" /></p>
<input type="submit" value="Pesquisar">
</form>
我的函数返回JSON:
@app.route('/userQuery', methods=['GET'])
def returnOne():
dao = Dao()
nome = request.args.get('nome')
return jsonify(json.loads(dao.select(nome)))
提交表单后的HTML页面。 我们称它为response.html
<!DOCTYPE html>
<html>
<head>
<title>hello</title>
</head>
<body>
<p id="test"></p>
<p id="test1"></p>
<script>
var b = JSON.parse('{{ a | tojson | safe}}');
document.getElementById('test').innerHTML = b.test;
document.getElementById('test1').innerHTML = b.test1;
console.log(b);
</script>
</body>
</html>
您的flask函数发送JOSN
并重定向到response.html
@app.route('/userQuery', methods=["POST", "GET"])
def returnOne():
a = {
"test": "abcd",
"test1": "efg"
}
return render_template("response.html", a=a)
使用ajax请求。 该插件将HTML表单中的Submit按钮转换为Ajax Submit
<script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function(response) {
var result = jQuery.parseJSON(response);
$('#someDiv').innerHTML = result.res
});
});
</script>
使用正确的表格ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.