gpt4 book ai didi

php - 使用 AJAX 在 Codeigniter 中通过选择框过滤表上的数据

转载 作者:行者123 更新时间:2023-11-29 02:57:48 24 4
gpt4 key购买 nike

我在使用 AJAX 过滤表上的数据时遇到问题。我在页面上有一个选择框和表格。我想使用选择框过滤表中的数据。例如,如果用户在选择框中选择值“Ganjil”,则表格仅显示包含数据“Ganjil”的行。

AJAX 脚本:

<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:'<?php echo base_url("search/filter") ?>',
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>


Controller :

public function filter()
{
$this->load->helper('url');

$key = $this->input->post('semester');

if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}

echo json_encode($data);
}


型号:

public function getGanjil($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}

public function getGenap($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}

当我选择选择框表格的值时什么都不显示。

最佳答案

第一个解决方案:使用$key = $this->input->post('key');在 Controller 中访问键值对。所以在 AJAX 中调用 $key 是 Key。您不能像 $this->input->post('semester'); 那样访问 javascript 变量学期在你的代码中。

第二个解决方案:

在 ajax 调用中 url:'<?php echo base_url("search/filter/key/") ?>'+semester

在 Controller 方法中使用 $key='' 作为参数。

public function filter($key='')因为在您的 Controller 方法中没有可访问的 $key 。您应该在 Controller 中作为参数进行访问。所以你可以在模型中使用它。在您的情况下, Controller 中没有 $key 作为参数。

也在你的代码中使用

$key = $this->input->post($key); as we access $key thru parameter.

------------更新 1------------

根据您的要求,AJAX调用

<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("search/filter/key/") ?>'+semester,
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>

你的 Controller 应该是这样的 ->

public function filter($key = '')
{
$this->load->helper('url');

if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}

echo json_encode($data);
}

关于php - 使用 AJAX 在 Codeigniter 中通过选择框过滤表上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com