0

I am having problems remembering how to loop through an object to manipulate it into options in a select form object. I have gotten this far but the alert from inside the success function simply prints "object Object". I have done this before but I am just rusty and any help is appreciated.

function getDestinations()
{
$.ajax({
    dataType:'json',
    type:'GET',
    url:"json/destinations.json",
    success:function(data) {
        for (var dest in data.Destinations) {
            alert(dest.destinationName)
        }

    }
});
}

The alerts are coming up as "undefined" but they are looping the correct amount of times.

For more information, each returned result is to populate a dropdown list that will in turn be used, when selected, to populate a div with weather information for said selected location using its "destinationID".

4

3 に答える 3

2
$.each(object, function(index,value){
    //do stuff
});
于 2013-05-15T18:21:24.553 に答える
1

これを試して -

success:function(data) {
        $.each(data.Destinations, function(i,v){
           alert(v.destinationName);
        });
}

移入するにはselect

  $("#selectID").empty();
  $.each(data.Destinations, function(i,v){
          var dest = v.destinationName;
          $("#selectID").append("<option value="+dest+">"+dest+"</option>");
  });
于 2013-05-15T18:22:50.520 に答える
1

他の答えは正しいですが、あなたがやっていることはうまくいかない理由です。for each ループを実行すると、変数は指定したインデックス/キーを反復処理します。

for (var dest in data.Destinations){
    // dest is an index/key within the data.Destinations variable
    // So you refer to it using
    alert(data.Destinations[dest].destinationName);
}

それが役立つことを願っています。

于 2013-05-15T18:25:54.773 に答える