首页 文章

从下拉列表中更新所选项目的表单字段(jquery,PHP和MySQL)

提问于
浏览
-1

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

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);

当我调用get_upsells.php(我手动检查)时会创建json字符串,但是在选择项目时我无法看到来自浏览器的任何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返回所选项目的值 . 也改为“返回”为“回声” .

仍然没有更新价格字段 .

更新:

将功能更改为:

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

用“你好”填充价格字段所以它看起来像......

response.price

...位没有传递数据 .

2 回答

  • 0

    type:'GET' 之后您有语法错误

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

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

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

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

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

  • 0

    现在修复:

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

相关问题