将javascript变量链接到Flask
这是我的index.html文件将javascript变量链接到Flask,javascript,python,jquery,json,flask,Javascript,Python,Jquery,Json,Flask,这是我的index.html文件 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript"> // setup some JSON to use var cars = [ { "make":"Porsche", "model":"911S" }, { "make":
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork()
};
}
function doWork() {
// ajax the JSON to the server
$.post("result", JSON.stringify(cars), function(){
});
// stop link reloading the page
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<form action = "/result" method = "POST">
<button id = "theButton" class ="button">
<span>
<i >Click</i>
</span>
</button>
<form>
运行命令行并单击后,单击按钮。我在Chrome控制台中得到了我想要的东西。
为了进入,我将注释event.preventDefault()。但是,当我再次运行时,它显示出错误请求未能解码JSON对象:期望值:第1行第1列(char 0)
有没有办法解决这个问题?在index.html文件中,创建一个占位符,由处理AJAX请求的js代码填写:
占位符
然后,在python代码中,您实际上不需要遍历模板,可以直接返回字符串:
@app.route('/result',methods=['POST',“GET”])
def worker():
data=request.get_json(force=True)
返回数据[0]['make']
然后,在js中,获取结果并将其放入占位符范围:
函数doWork(){
$.post(“结果”,JSON.stringify(cars),函数(回复){
$('ajax#u result')。文本(回复);
});
event.preventDefault();
}
点击按钮,享受您的保时捷 太好了,谢谢你的帮助。但是您知道为什么即使js变量显示在控制台上,也不能将其传递到结果页面吗?我们是否可以将其传递到结果页?我只是想知道这一点,这样我在未来的项目中可以更灵活。
#!flask/bin/python
import sys
from flask import Flask, render_template, request, redirect, Response
import random, json
app = Flask(__name__)
@app.route('/')
def output():
# serve index template
return render_template('index.html')
@app.route('/result', methods = ['POST', "GET"])
def worker():
# read json + reply
data = request.get_json(force = True)
print(data)
return render_template('result.html', result = data[0]["make"])
if __name__ == '__main__':
# run!
HOST = '127.0.0.1'
PORT = 4100
app.run(HOST, PORT, debug = True)