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

按钮点击无法跳转到目标URL问题求助

按钮无法跳转页面的问题排查与解决

核心问题分析

  • 视图函数被无限阻塞:get_result里用了client.loop_forever(),这是一个无限循环,会一直占用线程,永远执行不到后面的return render(...),服务器无法返回响应,浏览器自然跳不过去。
  • 表单与按钮逻辑冲突:按钮套在method="POST"的表单里,虽按钮是type="button"不会触发表单提交,但部分浏览器可能出现异常行为,干扰跳转逻辑。

解决步骤

1. 修改MQTT循环为非阻塞模式

替换loop_forever()为后台线程循环,添加等待逻辑避免无限阻塞:

def get_result(request):
    result = None

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code "+str(rc))
        client.subscribe("a",)
    
    def on_message(client, userdata, msg):
        nonlocal result
        result = msg.payload.decode("utf-8")
        print("Received message:", result)
        # 收到消息后主动断开连接
        client.disconnect()

    client = mqtt.Client("p1")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("127.0.0.1", 1883)
    
    # 启动后台循环线程
    client.loop_start()
    client.publish("test", 'C:/Users/HP/Desktop/reallifeviolencesituation/NV_4.mp4')

    # 设置超时等待(10秒,可按需调整)
    import time
    timeout = 10
    start_time = time.time()
    while result is None and time.time() - start_time < timeout:
        time.sleep(0.1)
    
    # 停止后台循环
    client.loop_stop()

    context = {'result': result}
    return render(request, "result.html", context)

这里用nonlocal替代全局变量,避免污染全局空间,同时添加超时机制防止无限等待。

2. 优化前端跳转逻辑

去掉不必要的表单标签,或用链接模拟按钮,更符合语义:

<!-- 方案1:直接保留按钮,移除外层form标签 -->
<input type="button" name="Show Result" onclick="location.href='{% url 'get_result' %}'" 
value="Show Result">

<!-- 方案2:用a标签模拟按钮,更符合跳转场景 -->
<a href="{% url 'get_result' %}" style="display:inline-block; padding: 4px 12px; border:1px solid #ccc; background:#f5f5f5; text-decoration:none; color:#333;">Show Result</a>

3. 额外检查项

  • 确认本地MQTT服务是否正常运行在127.0.0.1:1883,否则视图连接会卡住导致超时。
  • 检查urls.py中是否正确导入get_result视图,URL配置无误。
  • 打开浏览器控制台(F12),查看Network面板,点击按钮后是否有请求发送到/get_result/,通过状态码和响应内容定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:22:15