【问题标题】:Why my flask app is not redirecting after AJAX request?为什么我的烧瓶应用程序在 AJAX 请求后没有重定向?
【发布时间】:2021-12-24 11:42:08
【问题描述】:

我正在制作一个网络应用程序来帮助残疾人浏览互联网。它通过 JavaScript 接收语音命令并将命令发送到 Python app.py Flask 应用程序。然而,奇怪的是它并没有以任何方式重定向并给我 500 内部服务器错误。

这是发送命令的 JavaScript 函数 -

// 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 烧瓶应用程序 -

# 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")

我在这里有什么错?

【问题讨论】:

    标签: javascript python html ajax flask


    【解决方案1】:

    您将无法在 POST 请求中从烧瓶重定向。而是使用return 200

    那么你的 Ajax 请求中的成功函数应该会触发。

    如果需要更大的灵活性,还可以将json数据返回给“成功”或“错误”函数。 return json.dumps({'success' : True}), 200, {'ContentType' : 'application/json'}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多