2010-06-16 108 views
3

感謝您的期待PHP和JSON評論幫助

我的問題是,我似乎無法讓jquery顯示我生成的數據。

這裏是我的JSON輸出

("posts":[{"id":"1-2","time":"0","name":"dash","avatar":"http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG","comment":"rtetretrete tet rt uh utert"},{"id":"2-2","time":"0","name":"james","avatar":"http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG","comment":"fsdfdfsdf\r\n"}]) 

這裏是我的jQuery

$(document).ready(function(){ 
     var url="comments.php"; 
     $.getJSON(url,function(json){ 
      $.each(json.posts,function(i,post){ 
$("#content").append(
    '<div class="post">'+ 
     '<h1>'+post.name+'</h1>'+ 
     '<p>'+post.comment+'</p>'+ 
     '<p>added: <em>'+post.time+'</em></p>'+ 
     '<p>posted by: <strong>'+post.name+'</strong></p>'+ 
     '<p>avatar: <strong>'+post.avatar+'</strong></p>'+ 
    '</div>' 
); });  
}); 
    }); 
+1

這是什麼都用PHP做什麼? – 2010-06-16 08:22:25

+0

json是由php生成的。實際問題與此無關,但涉及到。 – 2010-06-17 12:24:43

回答

2

我剛纔想驗證使用http://www.jsonlint.com/

您的JSON,但失敗:

syntax error, unexpected TINVALID, expecting '{' or '[' at line 1 
Parsing failed 

整體(外)括號需要從()改爲{}這將驗證您的JSON和腳本應該可以正常

1

我沒有JSON檢查語法適合你,但如果它是正確的,那麼嘗試這在發送輸出之前(在PHP文件中)

header ('Content-type: application/json'); 
1

您的Json對象缺少前導和尾隨大括號,因此無效。 嘗試添加他們:

{"posts":[{"id":"1-2","time":"0","name":"dash","avatar":"http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG","comment":"rtetretrete tet rt uh utert"},{"id":"2-2","time":"0","name":"james","avatar":"http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG","comment":"fsdfdfsdf\r\n"}]} 
0

JSON應該是

{ 
    "posts": [ 
     { 
      "id": "1-2", 
      "time": "0", 
      "name": "dash", 
      "avatar": "http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG", 
      "comment": "rtetretrete tet rt uh utert" 
     }, 
     { 
      "id": "2-2", 
      "time": "0", 
      "name": "james", 
      "avatar": "http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG", 
      "comment": "fsdfdfsdf\r\n" 
     } 
    ] 
} 

使用jsonLint驗證JSON ..