codeigniter相关的下拉与jquery和ajax post [英] codeigniter - dependent dropdown with jquery and ajax post
问题描述
view: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 post。
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:
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'])));
}
}
数据来自ajax post后的数据库我检查过
The data is coming from the database after ajax post which I checked by
console.log(data.name);
console.log(data.id_type)
但无法找出如何使用我的视图的第二个下拉列表中的数据。
But couldn't able to figure out how to use the data in the second dropdown of my view.
我的意思是我如何填充第二个下拉列表,我在ajax post后收到的数据。
I mean how can i populate the second dropdown with the data i have received after ajax post.
推荐答案
我通过修改ajax post的成功函数找到了我的问题的解决方案:
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 post的成功函数中,并附加了值。它的工作,但有一个问题,当我更改第一个下拉选择新值出现,但显示为上一个选择的值不会消失。
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.
这篇关于codeigniter相关的下拉与jquery和ajax post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!