0

我在记住如何遍历对象以将其操作为选择表单对象中的选项时遇到问题。我已经做到了这一点,但是来自成功函数内部的警报只是打印“对象对象”。我以前做过这个,但我只是生疏了,任何帮助表示赞赏。

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

    }
});
}

警报以“未定义”的形式出现,但它们循环的次数正确。

有关更多信息,每个返回的结果将填充一个下拉列表,该下拉列表将在被选中时用于使用其“destinationID”填充具有所述所选位置的天气信息的 div。

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

The other answers are correct, but here is why what you are doing isn't working. When you do a for each loop, the variable iterates through the indexes/keys in whatever you give it.

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);
}

I hope that helps.

于 2013-05-15T18:25:54.773 回答