簡體   English   中英

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

我們選擇第一個選擇框內容時,需要從數據庫中添加一些數據到第二個選擇框,我們差不多完成了事情,但第二個選擇框沒有顯示任何值,請幫我們解決上述問題

你需要做兩件事:

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。

我嘗試使用一些硬代碼值的代碼,它完美地工作正常: -

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文件中的一些其他錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM