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

无需刷新页面:实现JS与Python实时交互计算股票总价

实时计算股票买入总价解决方案

需求说明

开发模拟股票交易网站的买入页面,实现:用户输入股票代码(symbol)和购买数量(shares)时,总价实时显示在id为render的<h1>标签中。该功能需要通过前端发送请求到后端,由后端查询股票单价并计算总价后返回,再更新页面。


后端实现(app.py)

完善/show_price路由,接收前端传来的股票代码和数量,查询股票单价并计算总价,以JSON格式返回结果:

from flask import request, jsonify
import requests  # 用于调用股票API,需提前安装:pip install requests

@app.route("/show_price", methods=["POST"])
def show_price():
    # 获取前端发送的参数
    symbol = request.json.get("symbol", "").strip().upper()
    shares = request.json.get("shares", "")
    
    # 验证输入合法性
    if not symbol or not shares.isdigit() or int(shares) <= 0:
        return jsonify({"error": "请输入有效的股票代码和正整数数量"}), 400
    
    # 调用股票API获取单价(示例用Alpha Vantage,可替换为你使用的API)
    # 注意:需替换为你的API Key,或使用其他免费/付费股票API
    api_key = "YOUR_API_KEY"
    try:
        response = requests.get(
            f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={api_key}"
        )
        data = response.json()
        price = float(data["Global Quote"]["05. price"])
    except Exception as e:
        return jsonify({"error": "无法获取股票价格,请检查代码是否正确"}), 500
    
    # 计算总价
    total_price = price * int(shares)
    # 返回JSON格式结果
    return jsonify({
        "symbol": symbol,
        "price_per_share": round(price, 2),
        "shares": int(shares),
        "total_price": round(total_price, 2)
    })

后端代码说明

  • 使用POST方法接收JSON格式的请求参数,比GET更适合传递结构化数据
  • 先验证输入:股票代码非空、数量是正整数,避免无效请求
  • 调用第三方股票API获取单价(这里用Alpha Vantage作为示例,可根据实际情况替换)
  • 计算总价后,用jsonify返回JSON数据,方便前端解析
  • 加入异常处理,捕获API调用失败的情况,返回友好错误信息

前端实现(HTML中的<script>标签)

在买入页面的<script>中添加事件监听和请求逻辑:

<script>
// 获取DOM元素
const symbolInput = document.getElementById('symbols');
const sharesInput = document.getElementById('shares');
const renderElement = document.getElementById('render');

// 定义更新总价的函数
async function updateTotalPrice() {
    const symbol = symbolInput.value.trim().toUpperCase();
    const shares = sharesInput.value.trim();
    
    // 清空显示,若输入不合法
    if (!symbol || !shares || isNaN(shares) || parseInt(shares) <= 0) {
        renderElement.textContent = '';
        return;
    }
    
    try {
        // 发送POST请求到后端/show_price路由
        const response = await fetch('/show_price', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ symbol, shares })
        });
        
        // 解析响应数据
        const data = await response.json();
        
        if (response.ok) {
            // 成功获取数据,更新页面显示
            renderElement.textContent = `总价: $${data.total_price.toFixed(2)} (单价: $${data.price_per_share} × ${data.shares}股)`;
        } else {
            // 后端返回错误,显示错误信息
            renderElement.textContent = `错误: ${data.error}`;
        }
    } catch (error) {
        // 网络或其他异常,显示提示
        renderElement.textContent = '网络错误,请稍后重试';
    }
}

// 给两个输入框添加输入事件监听,实时触发更新
symbolInput.addEventListener('input', updateTotalPrice);
sharesInput.addEventListener('input', updateTotalPrice);
</script>

前端代码说明

  • 先获取需要操作的DOM元素:两个输入框和显示总价的<h1>
  • 定义updateTotalPrice异步函数,负责发送请求和更新页面
  • 使用fetch发送POST请求,设置请求头为application/json,并将参数转为JSON字符串放在请求体中
  • 处理响应:如果请求成功,格式化总价并显示;如果失败,显示后端返回的错误信息
  • 给两个输入框绑定input事件,用户每输入一个字符都会触发更新,实现“实时”效果
  • 加入异常处理,捕获网络请求失败的情况

注意事项

  1. 替换后端代码中的YOUR_API_KEY为你实际使用的股票API密钥,或更换为其他可用的股票数据源
  2. 确保前端和后端的请求方式、参数格式一致(这里用JSON格式传递数据)
  3. 可以根据需求调整页面显示的样式和文本内容
  4. 若使用其他股票API,需调整后端中解析返回数据的逻辑,适配API的返回格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:31:04