2011-09-09 36 views
0

我目前在做一些jQuery的下面,JSON得到無法訪問返回未定義

$(".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變種成一個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關鍵?

回答

1

這是正確的

data.template[0].letter_template_content 
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", 
     },... 
    ] 
}