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

JQuery Ajax始终返回相同值问题排查求助

问题概述

表单包含bet和choice两组单选框,用户选择投注金额与猜测数字(1-4)后提交至roll.php。通过PHP脚本生成随机数判断输赢时,使用jQuery Ajax提交始终返回choice=1、bet=1000,但注释Ajax改用普通表单提交结果正常。

问题原因分析
  1. HTML中ID重复定义:所有bet单选框的ID均为bet,所有choice单选框的ID均为choice。DOM规范中ID必须唯一,使用$("#choice").val()或$("#bet").val()时,只会返回页面中第一个匹配该ID的元素值——也就是默认选中的1和1000,无法识别用户选中的其他选项。
  2. Ajax取值逻辑错误:代码直接通过ID获取元素值,没有针对选中的单选框进行取值,无法捕获用户的选择操作。
修复方案

步骤1:修正HTML的ID(可选但符合规范)

将重复的ID改为唯一值,或直接移除ID(单选框通过name属性分组,ID并非必需)。示例修改:

<!-- bet组示例 -->
<input name="bet" type="radio" value="1000" id="bet_1000" checked/>
<input name="bet" type="radio" value="10000" id="bet_10000"/>

<!-- choice组示例 -->
<input name="choice" type="radio" value="1" id="choice_1" checked/>
<input name="choice" type="radio" value="2" id="choice_2"/>

步骤2:修正Ajax的取值逻辑

两种可选方式:

方式一:精准获取选中的单选框值

修改formData的赋值逻辑,针对选中的单选框取值:

var formData = {
  choice: $("input[name='choice']:checked").val(),
  bet: $("input[name='bet']:checked").val() 
};

方式二:直接序列化整个表单(更简洁)

利用jQuery的serialize()方法自动序列化表单内所有有效字段,无需手动构建数据:

$(document).ready(function () {
  $("form").submit(function (event) {
    var formData = $(this).serialize();

    $.ajax({
      type: "POST",
      url: "inc/roll.php",
      data: formData,
      dataType: "json",
      encode: true,
    }).done(function (data) {
      var resultHtml = "";
      if (data.status === "winner") {
        resultHtml = `Status: ${data.status}<br />Results: ${data.results}<br />Choice: ${data.choice}<br />Bet: ${data.bet}<br />You won: ${data.prize}`;
      } else if (data.status === "loser") {
        resultHtml = `Status: ${data.status}<br />Results: ${data.results}<br />Choice: ${data.choice}<br />You lost: ${data.bet}`;
      }
      document.getElementById('results').innerHTML = resultHtml;
    });

    event.preventDefault();
  });
});

额外提示

PHP脚本中roll_dice()函数返回$roll % 4,可能得到0值,当前逻辑中如果结果为0会重新调用函数但未赋值给$results,会导致结果为0时无法进入判断。可修正为:

$results = roll_dice();
while ($results == 0) {
  $results = roll_dice();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:27:05