将 json 数据追加到 HTML 列表框


Append json data to HTML List box

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文件中的其他错误。

你需要做两件事:

1) 在 while 循环中连接结果。您正在重新分配数组变量,导致最新的数组变量覆盖旧的数组变量。这样,只会附加旧值。

改变

$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';

$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';

2) 改变

$('#freeitem').html(response.fritm);

$('#freeitem').append(response.fritm);

因为您只是附加要下拉的选项,而不是更改其 HTML。