查看:learning_view.php
view : learning_view.php
下面是我从数据库填充第一个下拉。
Here is the first dropdown which I am populating from database.
<select name = 'category' id = 'category'>
<option value="">-- Select Category --</option>
<?php foreach($category as $item){ ?>
<option value="<?php echo $item->id_cat; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
<br><br>
我要的是填充另一个下拉这取决于第一个下拉。对于我已经使用了jQuery的ajax帖子。
What I want is to populate another dropdown which is dependent on the first dropdown. For that I have used the jQuery ajax post.
第二个下拉列表:
<select name = 'type' id = 'type'>
<option value="">-- Select Type --</option>
<?php foreach($type as $item){ ?>
<option value="<?php echo $item->id_type; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
<br><br>
阿贾克斯后:
ajax post:
jQuery(document).ready(function(){
$("#category").change(function() {
var category_id = {"category_id" : $('#category').val()};
console.log(category_id);
$.ajax({
type: "POST",
data: category_id,
url: "<?= base_url() ?>learning/dependent_dropdown",
success: function(data){
$.each(data, function(i, data){
console.log(data.name);
console.log(data.id_type)
});
}
});
});
});
控制器:learning.php
controller : learning.php
public function dependent_dropdown()
{
if(isset($_POST['category_id']))
{
$this->output
->set_content_type("application/json")
->set_output(json_encode($this->learning_model->getType($_POST['category_id'])));
}
}
将数据从阿贾克斯后门柱的数据库,我检查
The data is coming from the database after ajax post which I checked by
console.log(data.name);
console.log(data.id_type)
在控制台中。
in the console.
但不能能弄清楚如何使用数据在我看来,第二个下拉。
But couldn't able to figure out how to use the data in the second dropdown of my view.
我的意思是我怎么能填充第二个下拉与我阿贾克斯后门柱已经接收到的数据。
I mean how can i populate the second dropdown with the data i have received after ajax post.
我找到了解决我的问题,通过修改的AJAX后成功函数
I found a solution to my problem by modifying the success function of the ajax post
success: function(data){
$.each(data, function(i, data){
$('#type').append("<option value='"+data.id_type+"'>"+data.name+"</option>");
});
}
这追加值到下拉。
Which append the value into the drop down.
<select name = 'type' id = 'type'>
<option value="">-- Select Type --</option>
</select>
我只是给了选择块的ID进入的AJAX后取得成功的功能和附加价值。它的工作原理,但有一个问题,就是当我改变了一个下拉新的价值选择出现,但它被显示为previous选择的值不会消失。
I just gave the id of the select block into the success function of the ajax post and appended the value. It works but there is a problem which is when I change the selection of the first dropdown new value appears but the values which were showing for the previous selection doesn't go away.