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

Python Flask点击按钮切换API随机图片不生效问题排查

问题原因

代码存在3个核心问题导致点击按钮后图片无法更新:

  • /getimage接口逻辑错误:该接口直接调用了首页路由函数next_image(),而这个函数的返回值是渲染完成的整页HTML内容,不是单独的图片地址,前端通过response.url根本取不到有效值
  • 存在语法笔误:import requests代码下方多了一行孤立的字符i,运行时会直接触发语法报错
  • 前后端数据格式不匹配:前端AJAX请求期望拿到JSON格式的图片地址响应,但后端没有返回标准JSON,前端也没有声明预期响应类型,解析失败后不会更新图片的src属性
修正后的代码

后端 main.py

from flask import Flask, render_template, jsonify
import requests

app = Flask(__name__)

# 抽离公共的猫图获取逻辑,避免重复代码
def fetch_random_cat_url():
    # 请将API-KEY替换为你自己的The Cat API密钥
    resp = requests.get('https://api.thecatapi.com/v1/images/search?api_key=API-KEY')
    return resp.json()[0]['url']

@app.route('/', methods=['GET'])
def index():
    cat_image = fetch_random_cat_url()
    return render_template("index.html", cat_image=cat_image)

@app.route("/getimage")
def get_img():
    new_cat_url = fetch_random_cat_url()
    # 返回标准JSON格式数据,和前端取值逻辑匹配
    return jsonify({"url": new_cat_url})

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

前端 templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Cats Images</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
    <h1>Random Cat Images</h1>
    <input type="button" id="mybutton" value="View Next "/>
    <div>
       <img src="{{cat_image}}" id="myimg" alt="Cat Image">
    </div>

    <script>
    $(document).ready(function() {
       $('#mybutton').click(function(){
           $.ajax({
               url: "{{ url_for('get_img') }}",
               type: "GET",
               dataType: "json", // 明确指定按JSON格式解析响应
               success: function(response) {
                   $("#myimg").attr('src', response.url);
               }
           });
       });
    });
    </script>
</body>
</html>
修正说明
  • 移除了原代码中多余的孤立字符i,修复语法错误
  • 将获取随机猫图URL的逻辑抽为独立公共函数,避免首页路由和接口路由重复编写请求代码
  • 调整/getimage接口逻辑,不再返回完整HTML页面,通过Flask内置的jsonify方法返回标准JSON结构,和前端response.url的取值逻辑完全对应
  • 前端AJAX请求新增dataType: "json"参数,强制jQuery按JSON格式解析响应,避免格式解析异常
  • 修正原代码中语义不符的函数命名:原首页路由函数名next_image不符合路由命名规范,改为通用的index

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 19:09:21