You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无刷新更新Flask:Ajax连接Flask的JavaScript报404错误求助

解决Flask + Ajax无刷新更新时的404错误问题

嘿,我来帮你排查一下这个404错误的问题,大概率是路由匹配或者请求配置出了问题,咱们一步步来:

1. 先检查最容易犯的拼写错误

你JS代码里的请求路径是/predicton,这看起来像是少写了一个字母——应该是/prediction吧?Flask的路由是严格匹配路径的,哪怕一个字母错了,都会返回404。先把这个拼写修正过来试试。

2. 确认Flask后端的路由配置是否正确

你得确保Flask应用里有对应的POST路由,而且请求方法、路径完全匹配。举个正确的示例:

from flask import Flask, request, jsonify

app = Flask(__name__)

# 注意路径是/prediction,且允许POST方法
@app.route('/prediction', methods=['POST'])
def prediction():
    # 根据你发送的数据格式获取内容,如果是JSON格式就用get_json()
    user_input = request.get_json().get('rawText')
    # 这里写你的业务逻辑,比如生成机器人回复
    bot_response = f"收到你的消息:{user_input}"
    # 返回JSON格式的响应
    return jsonify({'response': bot_response})

if __name__ == '__main__':
    app.run(debug=True)

别忘了导入request和jsonify,这俩是处理请求和返回JSON的关键模块。

3. 完善Ajax请求的配置

你提供的JS代码里dataType没写完,我给你补全一个完整的示例,确保请求格式和后端匹配:

function getBotResponse() {
    var rawText = $("#textInput").val();
    var userHtml = '<p class="userText"><span>' + rawText + '</span></p>';
    $("#textInput").val("");
    $("#chatbox").append(userHtml);
    document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});

    $.ajax({
        type: 'POST',
        url: '/prediction',  // 这里修正拼写
        dataType: 'json',  // 告诉jQuery预期返回JSON格式
        contentType: 'application/json',  // 发送JSON格式的数据
        data: JSON.stringify({rawText: rawText}),  // 把数据转成JSON字符串
        success: function(response) {
            // 成功收到响应后,把机器人回复添加到聊天框
            var botHtml = '<p class="botText"><span>' + response.response + '</span></p>';
            $("#chatbox").append(botHtml);
            document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
        },
        error: function(xhr, status, error) {
            // 加个错误日志,方便排查问题
            console.log('请求失败:', error);
            console.log('状态码:', xhr.status);
        }
    });
}

如果你的后端是用表单格式接收数据(比如request.form.get('rawText')),那可以去掉contentType和JSON.stringify,直接写data: {rawText: rawText}就行。

4. 其他排查小技巧

  • 打开浏览器的开发者工具(F12),切换到「网络」标签,看看请求的具体路径、状态码和响应内容,能直观看到哪里出问题。
  • 开启Flask的调试模式(app.run(debug=True)),控制台会打印所有请求的日志,能清楚看到Flask有没有接收到你的请求,以及路由匹配情况。

内容的提问来源于stack exchange,提问作者tapas r Mohanty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:27:16