json得不到访问返回为undefined

时间:2011-09-09 16:06:16

标签: javascript jquery json

我目前正在使用一些jQuery执行以下操作,

    $(".template-choice").live("click", function(event){$.post($(this).attr('href'), function(data) {
                console.log(data);
            $('.textarea textarea').val(data.letter_template_content);
     });
     event.preventDefault();
});

正如您所看到的,我尝试将JSON var插入到textarea中,但是我的data.letter_template_content正在返回,因为下面的undefined是我的JSON对象,

{"template":[{"letter_template_id":"1","letter_template_name":"Change of address","letter_template_content":"<p style=\"font-weight: bold;\">[Your Name] <\/p><p style=\"font-weight: bold;\">[Address] <\/p><p style=\"font-weight: bold;\">[Town, City] <\/p><p><span style=\"font-weight: bold;\">[Post Code] <\/span><br><\/p><p><br><\/p><p> <\/p><p>[Recipient Name] <\/p><p>[Job Title] <\/p><p>[Company Name] <\/p><p>[Address] <\/p><p>[Town, City] <\/p><p>[ Post Code] <\/p><p> <\/p><p> <\/p><p>Dear <span>[Recipient Name]<\/span>: <br><\/p><p><br><\/p><p> <\/p><p>This letter is to inform you that I have a new mailing address. Please update your records to replace my previous address: <br><\/p><p><br><\/p><p>[Previous Address] <\/p><p>[Town, City] <\/p><p><span>[Post Code]<\/span> <\/p><p> <\/p><p>with the following new address: <br><\/p><p><br><\/p><p>[New Address] <\/p><p>[Town, City] <\/p><p><span>[Post Code] <\/span><br><\/p><p><br><\/p><p> <\/p><p>Thank you for your attention to this matter. <br><\/p><p><br><\/p><p>[Your Name] <\/p>","letter_template_created":"2011-09-09 15:59:51"}]}

如何访问letter_template_name键?

2 个答案:

答案 0 :(得分:4)

那是因为data.letter_template_content不存在。

尝试:

data.template[0].letter_template_id
data.template[0].letter_template_name
data.template[0].letter_template_content

你的(非常格式化的JSON,我可以添加),在一个格式很好的世界中看起来像这样:

{
    template: [
        {
            letter_template_id: 1,
            letter_template_name: "Change of address",
            letter_template_content: "lots of html",
        },...
    ]
}

答案 1 :(得分:1)

这个是正确的

data.template[0].letter_template_content