Javascript 如何将Python Flask路由上的字符串发送到JS函数?
这是Javascript 如何将Python Flask路由上的字符串发送到JS函数?,javascript,python,flask,Javascript,Python,Flask,这是app.py app.route('/analyze', methods=['POST']) async def analyze(requestArg): img_data = await requestArg.form() img_bytes = await (img_data['file'].read()) img = open_image(BytesIO(img_bytes)) prediction = learn.predict(img)[0]
app.py
app.route('/analyze', methods=['POST'])
async def analyze(requestArg):
img_data = await requestArg.form()
img_bytes = await (img_data['file'].read())
img = open_image(BytesIO(img_bytes))
prediction = learn.predict(img)[0]
result(str(prediction))
我正试图将str(prediction)
发送到result()
函数的static/js/script.js
function result(str) {
$(".pd-result").show();
var resultText = $(".text")
switch (str) {
case "emotion":
text.html("angry");
break;
default:
break;
}
};
我试图直接调用
result(str(prediction))
,但它不起作用。在app.py
返回prediction
:
app.route('/analyze', methods=['POST'])
async def analyze(requestArg):
img_data = await requestArg.form()
img_bytes = await (img_data['file'].read())
img = open_image(BytesIO(img_bytes))
prediction = learn.predict(img)[0]
return prediction
在js文件中,在成功的post请求中调用函数:
$(() => {
Var data = {...};
$.post("/analyze", data)
.done((prediction)=>{
result(prediction)
}))
})
请参见此处:a)您不能随机(或非随机)混合使用JavaScript和Python b)Python代码在服务器上运行,而JS代码是客户端代码,因此在用户浏览器中运行。您需要使用向服务器的
/analyze
路由发出请求,然后在成功回调中处理结果。您是对的-您必须使用`$.post()`。这应该可以工作,因为您已经在使用jQuery。我修正了密码,谢谢!我对Ajax不太熟悉,所以我不确定哪里出了问题。