【问题标题】:Updating form field base on selected item from drop down (jquery, PHP & MySQL)根据下拉列表中的选定项目更新表单字段(jquery、PHP 和 MySQL)
【发布时间】:2014-03-27 20:36:06
【问题描述】:

我有一个数据库表,其中包含以下格式的预订附加信息:

name:price

我从数据库中获取了一个包含预订附加信息的 PHP 数组,并创建了一个包含其名称的选择框,并显示了一个价格字段:

<label class="label">Name</label>
<label class="select">
  <select id="name" name="name">
  <?php 
foreach ($upsells as &$upsell) {
  echo '<option value="'.$upsell['name'].'">'.$upsell['name'].'</option>';
}
  ?>
  </select>
</label>
<label id="pricet" class="label" style="display:none;">Price</label>
<label class="input" id="price" style="">
  <input class="" id="price" type="text" pattern="\d+(\.\d{2})?" name="price" value="" >
</label>

当从选择框中选择商品名称时,我正在尝试让价格框自动更新为与商品名称关联的正确价格。

使用 jquery,我有:

$(document).ready(function() {
  $("#name").change(function () {
    var choice = jQuery(this).val();
    $.ajax({
      url:'/get_upsell.php?pid=<?php echo $urlcrypt->encrypt($pid);?>',
      type:'GET',
      data : {'id' : choice},
      success : function(response) {
      $('input[name="name"]').val(response.name);
      $('input[name="price"]').val(response.price);
      }
    });
  });
})

还有get_upsell.php

if (isset($_GET['pid'])){
  $pid = $urlcrypt->decrypt($_GET['pid']);
}

$jsonupsells = $users->get_upsells_ajax($pid);

$indexedOnly = $jsonupsells;

foreach ($associative as $row) {
  $indexedOnly[] = array_values($row);
}

return json_encode($indexedOnly);

json 字符串是在我调用 get_upsells.php(我手动检查)时创建的,但在选择项目时我看不到来自浏览器的任何 ajax 请求。

我哪里出错了?

编辑:在 'GET' 之后发现了一个缺失的 。我现在看到了 ajax 请求,但不知道如何更新“价格”表单字段。

编辑:JS 函数现在看起来像这样:

$(document).ready(function() {
  $("#name").change(function () {
    var choice = jQuery(this).val();
    $.ajax({
      url:'/get_upsell.php?pid=<?php echo $urlcrypt->encrypt($pid);?>',
      type:'GET',
      data : {'id' : choice},
      success : function(response) {
        response = jQuery.parseJSON(response);
        $('input[name=price]').val(response.price);
      }
    });
  });
})

并更改了数据库查询,因此它仅根据项目 ID 返回所选项目的值。还将“return”更改为“echo”。

仍然没有更新价格字段。

更新:

将函数改为:

$('#price').val('Hello');

这会在价格字段中填充“你好”,所以它看起来像......

response.price

...bit 没有传递数据。

【问题讨论】:

  • 你能在 firebug 或开发者工具上看到 ajax 响应吗?

标签: php jquery mysql ajax


【解决方案1】:

type:'GET' 后出现语法错误

编辑:您需要解析为 JSON 对象。

success : function(response) {
response = jQuery.parseJSON(response);

在此之后要设置值,您需要删除引号。

$('input[name=acct]').val(response.price);

编辑 2:对于 ajax,您必须 echo JSON,而不是 return(在 php 文件中)

【讨论】:

    【解决方案2】:

    现在修复:

    $('#price').val(response[0].price);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2019-04-17
      • 2014-03-10
      相关资源
      最近更新 更多