基于JSON结果构建选择选项

Build select options based on JSON result

本文关键字:选择 选项 构建 结果 JSON 基于      更新时间:2023-09-26

我有这个JSON:

{
   "message":"",
   "entities":[
      {
         "city":"1",
         "state":"VE.01",
         "country":"VE",
         "name":"Maroa"
      },
      {
         "city":"2",
         "state":"VE.01",
         "country":"VE",
         "name":"Puerto Ayacucho"
      },
      {
         "city":"3",
         "state":"VE.01",
         "country":"VE",
         "name":"San Fernando de Atabapo"
      }
   ]
}

我需要基于cityname的结果构建一个选择选项。我有一个空的HTML select:

<select name="city" id="city">
    <option value="-1">Select a city</option>
</select>

而且,也许我错了,但我可以从结果(存储在data.entities javascript var)移动如下:

$each.(data.entities, function(){
  // here I should build the options
})

但我不知道该怎么做,谁能给我点鼓励或建议吗?

select#city应该是这样的:

<select name="city" id="city">
    <option value="-1">Select a city</option>
    <option value="1">Maroa</option>
    <option value="2">Puerto Ayacucho</option>
    <option value="3">San Fernando de Atabajo</option>
</select>

所有的答案都是我想要的,但看看我的代码:

$(".state").change(function() {
    state = $('.state option:selected').val();
    $.get(Routing.generate('cities') + '/VE/' + state).success(function(data) {
        if (data.message) {
            message = data.message;
        } else {
            $.each(data.entities, function(i, d) {
                $('#city').append('<option value="' + d.city + '">' + d.name + '</option>');
            });
        }
    }).error(function(data, status, headers, config) {
        if (status == '500') {
            message = "No hay conexión con el servidor";
        }
    });
});

我需要清理SELECT,但在附加新值之前留下默认选项<option value="-1">Select one</option>,我如何做到这一点?

try:

$('#city').empty().append('<option value="-1">Select a city</option>');
$.each(data.entities, function(i,d){  
 $('#city').append('<option value="'+d.city+'">'+d.name+'</option>');  
});
演示

试试:http://jsfiddle.net/K6Lf4/

$.each(data.entities, function(index,option){
  $("#city").append('<option value="'+option.city+'">'+option.name+'</option>');
});

如果我正确理解了你的问题,我认为这应该适合你

options = ''
$.each(data.entities,function(index,value){
    options += '<option value='+value.city+'>'+value.name+'</option>';
});
$('select').append(options)

try this

$.each(data.entities, function (key, val) {
    $("#city").append($("<option>", {value: val.city,text: val.name }));
});
演示