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

如何通过jQuery的AJAX请求从Python脚本获取返回变量?

如何通过AJAX获取Python脚本的输出?

首先得明确你现在遇到的两个核心问题:

1. 服务器未执行Python脚本,直接返回了源码

你的web服务器目前把test.py当成普通静态文本文件处理,所以AJAX请求拿到的是脚本代码,而非执行后的输出。要让服务器运行Python脚本并返回结果,你需要配置服务器或用Python web框架来处理请求。

2. Python脚本本身的写法错误

Python顶层代码里不能用return语句——return仅能在函数内部使用。如果要输出内容给前端,你需要用print()来输出指定内容。

接下来给你两种可行的解决办法,从简单到通用:

方法一:用Flask快速搭建后端(最适合测试)

这是最快能跑通的方案,无需复杂的服务器配置:

  1. 先安装Flask:
pip install flask
  1. 创建一个app.py文件,编写简单接口:
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/get-text', methods=['GET'])
def get_text():
    # 获取前端传过来的param参数
    input_param = request.args.get('param')
    # 这里可根据参数做逻辑处理,比如你原本的需求
    response_text = "Why hi there"
    # 返回JSON格式结果,方便前端解析
    return jsonify({"result": response_text})

if __name__ == '__main__':
    app.run(debug=True)
  1. 启动Flask服务:
python app.py
  1. 修改你的AJAX代码,指向Flask的接口:
function testPhy() {
    // 确保text是已定义的变量
    const text = "some input content";
    $.ajax({
        url: "http://localhost:5000/get-text",
        data: {param: text},
        success: function(dataR){
            console.log("LK: " + dataR.result)
        },
        error: function(request, status, error) {
            console.log("Error: " + error)
        }
    });
}
testPhy();

方法二:配置Web服务器执行CGI脚本(适合已有Apache/Nginx的场景)

如果你的项目已经在使用Apache或Nginx,可以通过CGI让服务器执行Python脚本:

  1. 把Python脚本放到服务器的CGI目录(比如cgi-bin),并在脚本开头添加shebang行(告诉服务器用Python解释器执行),同时输出正确的HTTP头:
#!/usr/bin/env python3
# 必须先输出HTTP内容类型头,否则服务器会报错
print("Content-Type: text/plain\n")
print("Why hi there")
  1. 给脚本添加执行权限(Linux/macOS下):
chmod +x test.py
  1. 修改AJAX的请求地址为CGI脚本的路径:
function testPhy() {
    $.ajax({
        url: "./cgi-bin/test.py",
        data: {param: text},
        success: function(dataR){
            console.log("LK: " + dataR)
        },
        error: function(request, status, error) {
            console.log("Error: " + error)
        }
    });
}
testPhy();

额外注意事项

  • 跨域问题:如果前端页面和Python服务不在同一个域名/端口下,会触发浏览器的跨域限制。Flask可安装flask-cors扩展解决:pip install flask-cors,然后在app.py里添加from flask_cors import CORS; CORS(app)。
  • 参数传递:确保前端的text变量已定义,否则AJAX会将undefined传给后端。

内容的提问来源于stack exchange,提问作者user10756438

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:36:55