2013-10-06 34 views
1

我從一個PHP腳本中獲得這個JSON,而且我目前正在使用該代碼。我想要做的是爲每個對象,將響應插入到div中。解析這個JSON併爲每個對象創建一個新的div

例如,我想將「句子」插入到div id =「句子」中,並將標題插入到div id =「title」中,並且我想爲每個新響應添加一個新的標題。

關於如何進行的任何提示?

<script type="text/javascript"> 
$(document).ready(function() { 
    console.log("warming up..."); 
    $.getJSON("response.php", function(data) { 
     console.log("got JSON"); 
     for (var i = 0; i < data.length; i++) { 
     var obj = data[i]; 
     console.log(obj.title); 
     } 
    }); 
});  
</script> 

這裏是JSON響應:

{ "sentences" : [ "The big irony behind the scorched-earth Republican offensive against President Obama’s health-care law is that its expansion of coverage to the uninsured would benefit House districts represented by Republicans nearly as much as those represented by Democrats.", 
     "Regardless of what other provisions they consider harmful, that posture unavoidably means House Republicans are seeking to 「protect」 a surprisingly large number of their constituents from the right to obtain health insurance with federal assistance.", 
     "Recently released census data show that, on average, the share of residents without insurance is almost as high in districts represented by House Republicans as in those represented by Democrats.", 
     "Slightly more Republicans (107) than Democrats (99) represent districts where the uninsured percentage is above the national average.", 
     "Massachusetts has the lowest percentage of uninsured due to its state-run health insurance, which has been in place since 2006." 
    ], 
    "summaryId" : "W76Z7a", 
    "title" : "Where Are the Uninsured Americans Who Will Benefit From Obamacare?" 
} 

回答

3

嘗試$.each()因爲data不是數組,它是一個對象。

$(document).ready(function() { 
    console.log("warming up..."); 
    $.getJSON("response.php", function (data) { 
     console.log("got JSON"); 

     $.each(data, function (key, obj) { 
      console.log(key, obj) 
      $('<div />', { 
       id: key, 
       text: obj 
      }).appendTo('body') 
     }); 
    }); 
}); 
+0

啊,哦,這是有道理的。非常感謝您的回答! – user2656127

相關問題