我有一个下拉列表,其中必须填充ajax响应。我在下拉列表中得到了额外的未定义选项。
频率下拉列表:
<div class="form-group">
<label class="control-label col-xs-3" for="frequenies">Frequencies:</label>
<div class="col-xs-9">
<select name="frequencies" id="frequencies-list" class="form-control">
<option value="">Select an option</option>
</select>
</div>
</div>
Ajax响应:
success: function(data){
alert(data);
var x = JSON.parse(data);
$.each(x, function() {
$.each(this, function(k, v) {
var frequencies = "<option value="+v.freq+">"+v.freq+"</option>";
$(frequencies).appendTo('#frequencies-list');
});
});
}
数据变量是一个编码的JSON:
[[{"freq":"1"},{"freq":"3"},{"freq":"6"},{"freq":"12"},{"freq":"24"},{"freq":"36"},{"freq":"48"},{"freq":"60"},{"freq":"72"},{"freq":"96"},{"freq":"120"},{"freq":"144"}],[{"ad_size_full":"Tab Page"},{"ad_size_full":"BRC's"},{"ad_size_full":"Cover tip"}],[{"ad_size_fractional":"2/3 Page"},{"ad_size_fractional":"1/2 Page Island"},{"ad_size_fractional":"1/2 Page"},{"ad_size_fractional":"1/3 Page"},{"ad_size_fractional":"1/4 Page"},{"ad_size_fractional":"1/6 Page"}],[{"color":"B&W"},{"color":"2 Color"},{"color":"3 Color / 4 color"},{"color":"5 Color"},{"color":"Matched Color"},{"color":"Matalic Color / PMS 800"}],[{"charge":"0.000000"},{"charge":"0.250000"},{"charge":"0.100000"},{"charge":"0.500000"},{"charge":"0.150000"},{"charge":"0.150000"},{"charge":"0.100000"}]]
v.freq在我的下拉列表中产生额外的"未定义"选项。我能得到帮助吗?
1
3
6
12
24
36
48
60
72
96
120
144
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
你需要的只是频率,对吗?这样怎么样:
$.each(x, function() {
$.each(this, function(k, v) {
if ("freq" in v) {
var frequencies = "<option value="+v.freq+">"+v.freq+"</option>";
$(frequencies).appendTo('#frequencies-list');
}
});
});
在下一个子array
中,没有索引freq
。尝试-
$.each(x, function() {
$.each(this, function(k, v) {
if (typeof v.freq != 'undefined') {
var frequencies = "<option value="+v.freq+">"+v.freq+"</option>";
$(frequencies).appendTo('#frequencies-list');
}
});
});
或者只循环通过第一个子数组。
或者简单地说:
$.each(x, function() {
$.each(this, function(k, v) {
if (v.freq) // will check for undefined, null, isNaN
{
var frequencies = "<option value="+v.freq+">"+v.freq+" </option>";
$(frequencies).appendTo('#frequencies-list');
}
});
});
尝试使用对象的第一个元素循环内部循环。
$.each(x, function() {
$.each(x[0], function(k, v) {
var frequencies = "<option value="+v.freq+">"+v.freq+"</option>";
$(frequencies).appendTo('#frequencies-list');
});
});