2011-04-23 38 views
1

我試圖讓jQuery把JSON文件放在一個簡單的網站上,當它按下按鈕時。 因此,JSON代碼如下所示:JSON + jQuery不工作

{ 
    "images" : [ 
     { "source" = "images1", "alternative" = "altImg1" }, 
     { "source" = "images2", "alternative" = "altImg2" }, 
     { "source" = "images3", "alternative" = "altImg3" } 
    ] 
} 

和HTML + jQuery的:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <head> 
     <title>jQuery</title> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
    </head> 

    <body> 
     <button>Press Me!</button> 
     <script> 
      $('button').click(function() { 
       $.getJSON('json-db.html', function(data) { 
        for(var i = 0; i < data.images.length; i++) { 
         var image = data.images[i]; 
         $('#result').append('<h1>' + image.source + ' ' + image.alternative + '</h1>'); 
        } 
       }); 
      }); 
     </script> 
     <div id="result">Result</div> 
    </body> 
</html> 

有沒有用Firebug的檢測到的錯誤。我多次重寫代碼,查找錯誤,將其與類似代碼等進行比較,但找不到任何內容。

在此先感謝!

回答

3

您的JSON對象是錯誤的

使用:,而不是像=

.......... 
"images" : [ 
    { "source" : "images1", "alternative" : "altImg1" }, 
    .................... 
] 
.......... 
+0

哦,多麼愚蠢的我是......非常感謝! – Tsvetan 2011-04-23 08:03:45

+1

我想jQuery優雅地擺脫了錯誤。嘗試使用json驗證器來挑選未來的小錯誤http://www.jsonlint.com/;) – 2011-04-23 08:05:40

+0

是的,我不喜歡web開發,因爲這(以及您需要編寫的代碼量)。再次感謝! – Tsvetan 2011-04-23 08:08:13