0

I'm doing Android PhoneGap project in my company. I have a JSON file and want to get it into my HTML select box. As I am still newbie, I haven't understand about JSON parsing mostly.

Here's my JSON File (city.json) :

[{"CityID":1,"CityName":"Magelang"},{"CityID":2,"CityName":"Jayapura"},{"CityID":3,"CityName":"Aceh"}]

I really didn't know whether it's needed to parsed or not. I have followed RaYell answer in this thread. Jquery getJSON populate select menu question

So, I code these to populate the result into the option in select box.

$.getJSON('city.json', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
    html += '<option value="' + data[i].CityID + '">' + data[i].CityName + '</option>';
}
$('#city').append(html);
});

But it didn't worked on my code. My select box has none options :( Any solutions? Thanks before.

4

2 回答 2

0

您的for循环不适用于对象。只有数组。

您需要使用for (var i in data) {来遍历对象的所有属性。

于 2013-05-14T05:02:50.340 回答
0

尝试执行$('#city').html(html);以查看错误是什么:

编辑:将此添加到$.getJSON通话末尾:

    $(document).ready(function(){
        $.getJSON(. . .).fail(function( jqxhr, textStatus, error ) {
             var err = textStatus + ', ' + error;
             alert( "Request Failed: " + err);
             });
    });
于 2013-05-14T04:44:48.680 回答