[英]How can I pass JSON of flask to Javascript
I have an index page, which contains a form, fill in the form and sends the data to a URL, which captures the input, and does the search in the database, returning a JSON. 我有一个索引页,其中包含一个表单,填写表单并将数据发送到URL,URL捕获输入,并在数据库中进行搜索,返回JSON。 How do I get this JSON, and put it on another HTML page using Javascript?
如何获取此JSON,并使用Javascript将其放在另一个HTML页面上?
Form of index: 索引形式:
<form action="{{ url_for('returnOne') }}", method="GET">
<p>Nome: <input type="text" name="nome" /></p>
<input type="submit" value="Pesquisar">
</form>
My function that returns JSON: 我的函数返回JSON:
@app.route('/userQuery', methods=['GET'])
def returnOne():
dao = Dao()
nome = request.args.get('nome')
return jsonify(json.loads(dao.select(nome)))
Your HTML page after you submit the form. 提交表单后的HTML页面。 let's call it
response.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>
Your flask function that sends JOSN
and redirects to response.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)
Use ajax request. 使用ajax请求。 This plugin transform the submit button in your HTML form to an Ajax submit
该插件将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>
Use the correct form Id 使用正确的表格ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.