微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 将json数据附加到HTML列表框

HTML代码是:

<select  name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select  name="freeitem" id="freeitem" class="form-control">
</select>

Js代码

function getPrice(val) {
  $.ajax({
    type: 'post',
    url: 'get_sales_price.PHP',
    data: {
      get_option: val
    },
    dataType: 'json',
    success: function(response) {
        console.log(response)
      $('#freeitem').html(response.fritm);

    }
  });
}

PHP代码是:

$option = $_POST['get_option'];
    $data = array(); 
    $prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
    while ($tqty = $prdqty->fetch_assoc()) 
    {
    $data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
    }
    echo json_encode($data);

我们选择第一个选择框内容时,需要从数据库添加一些数据到第二个选择框,我们差不多完成了事情,但第二个选择框没有显示任何值,请帮我们解决上述问题

解决方法:

我尝试使用一些硬代码值的代码,它完美地工作正常: –

Html Jquery(扩展名为.html的单页): –

<select  name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select  name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
  $.ajax({
    type: 'post',
    url: 'get_sales_price.PHP',
    data: {
      get_option: val
    },
    dataType: 'json',
    success: function(response) {
        console.log(response)
      $('#freeitem').html(response.fritm);

    }
  });
}
</script>

PHP(具有硬编码值): –

<?PHP
$option = $_POST['get_option'];
$data = array(); 
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);

输出: –

http://prntscr.com/auyn7i

http://prntscr.com/auymzf

http://prntscr.com/auynij

注意: – 问题可能正在发生,因为你错过了循环内部串联的jquery库或你的PHP文件中的一些其他错误.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐