[英]Why my flask app is not redirecting after AJAX request?
我正在制作一个 web 应用程序来帮助残疾人浏览互联网。 它通过 JavaScript 接收语音命令并将命令发送到 Python app.py Flask 应用程序。 然而,奇怪的是它没有以任何方式重定向并给我 500 内部服务器错误。
这是发送命令的 JavaScript function -
// This function sends command to python
function sendCommand(command){
let userCommand = {
"command": command
}
$.ajax({
type: "POST",
url: "/command",
data: JSON.stringify(userCommand),
contentType: "application/JSON",
dataType: 'json',
success: function(){
window.location.href = "temp.html";
}
})
}
这是 python flask 应用程序 -
# Importing required libraries and functions
from flask import Flask, render_template, request, redirect
import speech_recognition as sr
import sys
# Initiating Flask
app = Flask(__name__)
# Command Global variable
COMMAND = ""
# Route to Command (Index) page
@app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
# Processing Command
@app.route('/command', methods=["POST"])
def get_javascript_data():
if request.method == "POST":
JSONdict = request.get_json()
COMMAND = JSONdict["command"]
print(f'{COMMAND}', file=sys.stdout)
if "search" in COMMAND:
print("TODOSearch")
elif ("music" and "play") in COMMAND:
print("TODO")
else:
print("TODO")
return redirect("/redirect")
@app.route("/redirect")
def redirect():
return render_template("redirect.html")
我在这里有什么错?
您将无法在 POST 请求中从 flask 重定向。 而是使用return 200
然后您的 Ajax 请求中的成功 function 应该触发。
如果您需要更大的灵活性,您还可以将 json 数据返回到“成功”或“错误”function。 return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.