PHP和JSON评论帮助

时间:2010-06-16 08:20:37

标签: jquery 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>'
); });      
});
    });

4 个答案:

答案 0 :(得分:2)

我刚尝试使用http://www.jsonlint.com/

验证您的JSON

它失败了:

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

整体(外部)括号需要从()更改为{}这将验证您的JSON并且脚本应该可以正常工作

答案 1 :(得分:1)

我没有检查你的json的语法,但如果它是正确的,那么在发送输出之前尝试这个(在PHP文件中)

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

答案 2 :(得分: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"}]}

答案 3 :(得分: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 ..