【发布时间】:2021-10-04 05:36:38
【问题描述】:
我是 jquery 和 ajax 的新手。我真的需要你的帮助。
我有两个选择框,一个在选中第一个选择框时动态添加选项。我使用 ajax 来动态获取这些值。我从数据库中正确获取值。但是,当我尝试将这些选项附加到第二个选择框中时,它不起作用。我的代码如下
$(document).ready(function() {
$("#categories").change(function() {
var categoryId = $("#categories").val();
//alert(categoryId);
if(categoryId == 2) {
$.ajax({
url: "<?= base_url();?>Web/getRateType",
method: "POST",
dataType: "json",
success:function(data) {
//alert(data[0].status);
$("#rate_container").css('display', 'block');
$("#expected_salary_container").css('display', 'none');
$("#rate_categories").empty();
// var str = '<label>Rate*</label></br>';
//str += '<select name="rate_categories" style="font-size:15px" id="rate_categories"><option value="0">Select</option>';
var str = '';
$.each(data, function(key, value) {
//alert(value['rate_id']);
str +='<option value="'+ value['rate_id'] +'">'+ value['rate_cat_name'] +'</option>';
});
alert(str);
//str += '</select>';
var x = $("#rate_categories").append(str);
if(x){
alert(x);
}
}
});//$("#rate_categories").append('<option value="'+ value.rate_id +'">'+ value.rate_cat_name +'</option>');
}
else if (categoryId == 1) {
document.getElementById("expected_salary_container").style.display = "block";
document.getElementById("rate_container").style.display = "none";
}
else{
document.getElementById("expected_salary_container").style.display = "none";
document.getElementById("rate_container").style.display = "none";
}
});
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<?php foreach($categories as $key => $value) { ?>
<option value="<?php echo $value['type_id']; ?>"><?php echo $value['cat_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
这里的 alert(x) 工作正常。但 html 没有附加在选择框内。有人可以帮忙吗
标头中引用了jQuery:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
【问题讨论】:
-
alert(str);结果怎么样? -
正确显示选项值。
-
您是否在控制台中遇到任何错误?
-
只是我的猜测尝试像这样的选择器
$('select[name="rate_categories"]').append(str); -
控制台显示这个错误Uncaught ReferenceError: $ is not defined
标签: javascript php html jquery