我收到了json对象表单服务器,如下面的
{"locations": [{"locationCode": "Branch 1","locationName": "BR-001"},
{"locationCode": "Branch 2","locationName": "BR-002"},
{"locationCode": "Branch 3","locationName": "BR-003"}
]}
然后我需要为值附加 locationCode ,为文本
附加 locationName<option value="locationCode">locationName</option>
我试过这个但是不能这样做
var location = data.locations;
$.each(location, function (key, value) {
$('#newLocation')
.append($("<option></option>")
.attr("value", key)
.text(value));
});
答案 0 :(得分:3)
您正在迭代数组,即 locations
不在地图上
所以将代码更改为
var location = data.locations;
$.each(location, function (index) {
$('#newLocation')
.append($("<option></option>")
.attr("value", location[index].locationCode)
.text(location[index].locationName));
});
<强>更新: - 强>
答案 1 :(得分:1)
试试这个:
var locations =
[
{"locationCode": "Branch 1","locationName": "BR-001"},
{"locationCode": "Branch 2","locationName": "BR-002"},
{"locationCode": "Branch 3","locationName": "BR-003"}
];
for (var i=0;i<locations.length;i++){
var value = locations[i].locationCode;
var text = locations[i].locationName;
var opt = "<option value='"+value+"' >"+text+"</option>";
$('#newLocation').append(opt);
}
或者:
var loc = new Object();
var loc = {"locations":
[
{"locationCode": "Branch 1","locationName": "BR-001"},
{"locationCode": "Branch 2","locationName": "BR-002"},
{"locationCode": "Branch 3","locationName": "BR-003"}
]
};
for (var i=0;i<loc.locations.length;i++){
var value = loc.locations[i].locationCode;
var text = loc.locations[i].locationName;
var opt = "<option value='"+value+"' >"+text+"</option>";
$('#newLocation').append(opt);
}