目前,我的視圖類中有一個表,其中使用 codeigniter 中的 MVC 框架填充了來自后端的資料。現在我在每列上方都有一個下拉串列,用于填充我的資料庫中的相同記錄。因此,我希望能夠在用戶單擊下拉串列中的專案后立即過濾我的記錄。
我知道如何在單擊提交按鈕時過濾記錄,但我希望在用戶單擊下拉項時立即進行這種過濾,我假設我需要進行 AJAX 呼叫不熟悉。
到目前為止,我的視圖類中有這個:
<table>
<tr>
<th width="10%">Source</th>
</tr>
<tr>
<td width="5%"><select>
<option value="">All </option>
<?php if($sources) foreach($sources as $source): ?>
<option value="<?php echo $source['title'] ?>"><?php echo $source['title'] ?></option>
<?php endforeach;?>
</select></td>
</tr>
<tbody>
<?php
if(isset($records) && count($records) > 0)
{
foreach($records as $row ){
?>
<tr>
<td><?= $row->source ?></td>
</tr>
<?php } } ?>
</tbody>
這里默認選擇顯示 Any 并帶有空值以顯示所有記錄,并且后端資料下面有它們單獨的值。現在我想在這里進行實時過濾。另外這里我只包含了 1 個下拉串列,但是有多個下拉串列,所以它應該根據提供的所有下拉值進行過濾。
uj5u.com熱心網友回復:
只需創建一個 ajax 函式來在選項更改時接收請求:
$route['ajax_dropdown'] = 'your_controller/your_function'; // change ajax_dropdown to whatever you want
然后在您的控制器中:
function your_function()
{
$input_value = $this->input->get('your_input_name'); // get the input value of jQuery's get request
$data = array(); // store data in here
// do something like: $data['status'] = $this->your_model->get_status();
echo json_encode($data); // json_encode to make your data object become a string to send }
最后,在您看來,您可以發送 ajax 請求來獲取資料。我更喜歡使用 jQuery,所以我寫在這里:
<table>
<tr>
<th width="10%">Source</th>
</tr>
<tr>
<td width="5%">
<select id="your_id_name">
<option value="">All </option>
<?php if ($sources) foreach ($sources as $source) : ?>
<option value="<?php echo $source['title'] ?>"><?php echo $source['title'] ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tbody>
<?php
if (isset($records) && count($records) > 0) {
foreach ($records as $row) {
?>
<tr>
<td><?= $row->source ?></td>
</tr>
<?php }
} ?>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#your_id_name').on('change', function() {
$.get('<?php echo base_url('ajax_dropdown'); ?>', {
your_input_name: 'your_value' // input value of get request
}, function(res) {
var values = JSON.parse(res); // then do something
})
})
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/352259.html
上一篇:JavaScript實作跟隨廣告
下一篇:將資訊從AJAX傳遞到控制器類
