【问题标题】:jQuery updates hidden input value, but does not pass to POST variablejQuery 更新隐藏的输入值,但不传递给 POST 变量
【发布时间】:2015-11-09 08:07:33
【问题描述】:

我已经为地址数据构建了一个 HTML 表单,我想在通过 POST 变量将所有表单字段提交到 SQL 数据库之前计算地址的纬度和经度。

现在我的控制台显示我使用 lat/lng 值成功编辑了隐藏的“latInput”和“lngInput”字段 DOM。但是,我的 PHP 脚本中的 POST 变量并未捕获该更改。

隐藏的表单域

<input type="hidden" name="latInput" id="latInput" value="">
<input type="hidden" name="lngInput" id="lngInput" value="">

jQuery 设置/检查隐藏字段的 DOM 更新

//insert new lat/lng variables to the hidden form inputs, so PHP can access POST and insert into SQL database
$("#latInput").attr('value',localLat);
$("#lngInput").attr('value',localLng);

//confirm hidden input fields were set with lat/lng values
console.log("latInput set to: " + $("input[name=latInput]").val());
console.log("lngInput set to: " + $("input[name=lngInput]").val());

PHP 脚本检查 POST 变量的 lat/lng,并将所有字段提交到数据库

$lat = $_POST['latInput'];
$lng = $_POST['lngInput'];

echo('<p>POST variable for lat = '.$lat.'</p>');
echo('<p>POST variable for lng = '.$lng.'</p>');

//choose SQL fields (column names), then choose HTML form fields ("name" attribute)
$sql = "INSERT INTO $tablename (name,address1,city,state,zip,latitude,longitude) VALUES ('$_POST[firstName]','$_POST[address1]','$_POST[city]','$_POST[state]','$_POST[zipCode]','$_POST[latInput]','$_POST[lngInput]')";

请注意——所有其他表单字段(address1、city 等)都已成功传递 POST 变量并在提交时进入数据库。即使 DOM 正在更新隐藏的 latInput 和 lngInput 字段,这也不会影响我的本地 $lat 和 $lng 变量。 POST 仍然不返回任何值。我尝试使用如下所示的虚拟数据更新原始隐藏的 latInput 和 lngInput 字段,并且该虚拟数据可以正常通过。

虚拟数据

<input type="hidden" name="latInput" id="latInput" value="1.234">
<input type="hidden" name="lngInput" id="lngInput" value="2.345">

任何想法为什么会下降?

感谢您的帮助!

【问题讨论】:

    标签: php jquery forms dom post


    【解决方案1】:

    我遇到了同样的问题。 This answer 帮助了我。解决方案是使用 name 选择器而不是 id

    Form :

    <form id="my-form" action="post">
      <input type="hidden" name="latInput">
      <input type="hidden" name="lngInput">
      <input type="submit" value="Submit">
    </form>
    

    JQuery

    $('#my-form input[name=latInput]').val(localLat);
    $('#my-form input[name=latInput]').val(localLng);
    

    这些值将成功传递给 POST。

    【讨论】:

      【解决方案2】:

      设置输入值的正确方法是使用val()函数。

      $("#latInput").val(localLat);
      $("#lngInput").val(localLng);
      

      【讨论】:

      • Rejith 我原来用过这个,又试了一次——还是不行。我正在更新 #latInput 和 #lngInput 很好,但该值没有作为 POST 变量提交。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多