我正在尝试将jquery中的值附加到选择框。
html方面如下所示
<select class="form-control prod" name="SalesPerson" id="SalesPerson" required>
<!-- <option value="">Select Sales Person</option> -->
</select>
Ajax的代码片段如下所示
success: function(data){
console.log(data);
$.each(data, function(key, value) {
$('#SalesPerson').append("<option value='" + data.admin_id + "'>" + data.fname + "</option>");
});
}
});
当我做console.log(data);
我在
下面得到了这个输出[{"admin_id":"206","fname":"FLYJAC-1BR","lname":""},{"admin_id":"252","fname":"KAMAL","lname":"G"},{"admin_id":"253","fname":"WILLIAM","lname":"S"}]
但是数据没有附加到选择框。任何帮助表示赞赏。
答案 0 :(得分:2)
1. dataType: 'json'
需要添加到您的ajax调用中
2. data.admin_id
需要value.admin_id
等等。
工作代码段: -
data = [{"admin_id":"206","fname":"FLYJAC-1BR","lname":""},{"admin_id":"252","fname":"KAMAL","lname":"G"},{"admin_id":"253","fname":"WILLIAM","lname":"S"}];
$.each(data, function(key, value) {
$('#SalesPerson').append("<option value='" + value.admin_id + "'>" + value.fname + "</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control prod" name="SalesPerson" id="SalesPerson" required>
<!-- <option value="">Select Sales Person</option> -->
</select>
对于您的代码需要(正如您所说,您要删除旧选项,然后需要添加新选项): -
success: function(data){
var option_html = '';
$.each(data, function(key, value) {
option_html += "<option value='" + value.admin_id + "'>" + value.fname + "</option>";
});
$('#SalesPerson').html(option_html);
}
注意: -
如果您的ajax调用中没有dataType: 'json'
,那么在$.each()
代码之前:
data = $.parseJSON(data);