使用json对象追加选择值和文本

时间:2014-10-30 04:19:50

标签: javascript jquery json

我收到了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));
        });

2 个答案:

答案 0 :(得分:3)

您正在迭代数组,即 locations 不在地图上 所以将代码更改为

var location = data.locations;
        $.each(location, function (index) {
        $('#newLocation')
          .append($("<option></option>")
          .attr("value", location[index].locationCode)
          .text(location[index].locationName));
        });

<强>更新: -

DEMO

答案 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);
}