Reputation: 5523
So I have some less than desireable JSON being returned from a web service and it goes a little somethin like this (please excuse the '?' characters):
{
"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 "
]
}
I'm trying to populate a select list ('#state') but I keep getting 'undefined' Here's the ajax call - issue in success function:
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);
}
});
});
UPDATE: Reflecting first comment, now displays 'undefined' but has the correct number of 'undefined's'
UPDATE 2: I need the formatting to be<option value="AI">Appenzell Innerrhoden</option>
Upvotes: 0
Views: 940
Reputation: 19700
You could modify your $each
function parameter as below:
$.each(data.d,function(i,o){
var id = o.split(",")[0];
var value = o.split(",")[1];
toAppend += "<option value="+id+">"+value+"</option>";
});
The problem with your code was, you were accessing the JSON object
rather than the d
key inside it.
Upvotes: 1
Reputation: 24638
Please change:
toAppend += '<option>'+o.id+'</option>';
To:
toAppend += '<option value="' + o.split(',')[0] + '">' + o.split(',')[1] + '</option>';
Upvotes: 1