使用JSON数组填充选择列表

时间:2014-11-05 01:12:37

标签: jquery json

所以我从网络服务中返回了一些不太令人满意的JSON,它有点像这样(请原谅'?'字符):

{
    "d": [
      "AI,Appenzell Innerrhoden ", 
      "AR,Appenzell Ausserrhoden ", 
      "BE,Bern ", 
      "BL,Basel", 
      "BS,Basel", 
      "FR,Fribourg ", 
      "GE,Gen�ve ", 
      "GL,Glarus ", 
      "GR,Graub�nden ", 
      "JU,Jura ", 
      "LU,Luzern ", 
      "NE,Neuch�tel ", 
      "NW,Nidwalden ", 
      "OW,Obwalden ", 
      "SG,Sankt Gallen ", 
      "SH,Schaffhausen ", 
      "SO,Solothurn ", 
      "SZ,Schwyz ", 
      "TG,Thurgau ", 
      "TI,Ticino ", 
      "UR,Uri ", 
      "VD,Vaud ", 
      "VS,Valais ", 
      "ZG,Zug ", 
      "ZH,Z�rich "
    ]
}

我正在尝试填充选择列表('#state'),但我一直在'未定义' 这是ajax调用 - 成功函数中的问题:

var country = {};
country.request=$('#country').val();
$.ajax({
        type: 'POST',
        url: 'webserviceURL',
        crossDomain: true,
        data: JSON.stringify(country),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function(data){
          var toAppend = '';
           $.each(data.d,function(i,o){
            toAppend += '<option>'+o.id+'</option>';
          });
         $('#state').append(toAppend);
        },
        error: function (xhr, errorType, exception) {
            var errorMessage = exception || xhr.statusText;

            alert(errorMessage);
        }
    });
});

更新:反映第一条评论,现在显示“未定义”但具有正确数量的“未定义”

更新2:我需要格式为<option value="AI">Appenzell Innerrhoden</option>

2 个答案:

答案 0 :(得分:1)

请更改:

toAppend += '<option>'+o.id+'</option>';

要:

toAppend += '<option value="' + o.split(',')[0] + '">' + o.split(',')[1] + '</option>';

答案 1 :(得分:1)

您可以修改$each函数参数,如下所示:

$.each(data.d,function(i,o){
var id = o.split(",")[0];
var value = o.split(",")[1];
toAppend += "<option value="+id+">"+value+"</option>";
});

您的代码存在的问题是,您正在访问JSON object而不是其中的d密钥。