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

如何将JavaScript变量(如window.screen.width)传递至Flask后端?

嘿,这个需求我刚好经手过好几次,给你整理了三种能直接在Flask后端拿到前端JS变量的靠谱方法,完全不需要依赖响应式页面方案:

方法1:通过GET请求传递(简单直接)

这种方式最适合快速验证或者传递少量公开参数,比如屏幕宽度这种非敏感数据。

前端JS代码:
先获取到window.screen.width的值,然后构造带参数的URL跳转到Flask路由,或者用AJAX异步请求:

// 获取屏幕宽度
const screenWidth = window.screen.width;
// 方式1:直接跳转(同步)
window.location.href = `/receive-screen-width?width=${screenWidth}`;

// 方式2:异步AJAX请求(不跳转页面)
fetch(`/receive-screen-width?width=${screenWidth}`)
  .then(response => response.text())
  .then(data => console.log(data));

Flask后端代码:
用request.args.get()来获取URL里的参数:

from flask import Flask, request

app = Flask(__name__)

@app.route('/receive-screen-width')
def receive_screen_width():
    # 获取前端传过来的屏幕宽度,转成整数类型
    screen_width = request.args.get('width', type=int)
    # 这里就可以直接使用这个变量了,比如存数据库、做逻辑判断
    print(f"拿到的屏幕宽度是:{screen_width}px")
    return f"成功接收屏幕宽度:{screen_width}px"

if __name__ == '__main__':
    app.run(debug=True)
方法2:通过POST请求传递(适合非公开/大量数据)

如果不想让参数暴露在URL里,或者要传递更多数据,用POST请求+JSON格式更稳妥。

前端JS代码:
用fetch发送JSON格式的POST请求:

const screenWidth = window.screen.width;
// 可以同时传多个变量,比如屏幕高度
const screenHeight = window.screen.height;

fetch('/receive-screen-data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    width: screenWidth,
    height: screenHeight
  })
})
.then(response => response.json())
.then(data => console.log(data));

Flask后端代码:
用request.get_json()解析JSON数据:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/receive-screen-data', methods=['POST'])
def receive_screen_data():
    # 获取JSON格式的请求体
    screen_data = request.get_json()
    if screen_data:
        screen_width = screen_data.get('width')
        screen_height = screen_data.get('height')
        print(f"屏幕尺寸:{screen_width}x{screen_height}")
        return jsonify({"status": "success", "received_width": screen_width})
    return jsonify({"status": "error", "message": "未接收到数据"})

if __name__ == '__main__':
    app.run(debug=True)
方法3:通过隐藏表单提交(适合结合页面表单的场景)

如果你的页面本身有表单需要提交,可以把JS变量塞到隐藏的表单字段里,一起提交到后端。

前端HTML+JS代码:

<form id="screenForm" action="/submit-form" method="POST">
  <!-- 其他表单字段 -->
  <input type="hidden" id="screenWidthInput" name="screen_width">
  <button type="submit">提交</button>
</form>

<script>
// 页面加载完成后给隐藏字段赋值
window.onload = function() {
  const screenWidth = window.screen.width;
  document.getElementById('screenWidthInput').value = screenWidth;
};
</script>

Flask后端代码:
用request.form.get()获取表单里的隐藏字段值:

from flask import Flask, request

app = Flask(__name__)

@app.route('/submit-form', methods=['POST'])
def submit_form():
    screen_width = request.form.get('screen_width', type=int)
    print(f"从表单拿到的屏幕宽度:{screen_width}px")
    # 处理其他表单数据...
    return "表单提交成功"

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

这三种方法都能让你在Flask后端直接拿到window.screen.width这个变量,根据你的实际场景选就行——要是只是快速传个值,用GET;要保密或者传多数据用POST;有表单就用隐藏字段方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:23:35