Я хочу напечатать, как HTML, элементы из возвращаемого объекта JSON. Код рубина:
get '/get_template_info' do
mandrill = Mandrill::API.new
name = "blah"
result = mandrill.templates.info name
end
JQuery:
$(document).ready(function(){
$( ".result" ).on( "click", "#edit_template", function() {
$.getJSON("/get_template_info?name=blah", function(data) {
$.each( data, function( key, value ) {
var template_txt = '<p>' + this["code"] + '</p>';
$(".edit_div").append(template_txt);
});//end each
});//end json
});//end click
});//end doc
В консоли firebug это то, что я получаю:
{"slug":"blah","name":"blah","code":"blah is the message\r\n\r\n<p>and blah is how it is</p>\r\n<p> I hope it gets better soon </p>","publish_code":"blah is the message\r\n\r\n<p>and blah is how it is</p>\r\n<p> I hope it gets better soon </p>","published_at":"2014-02-06 03:36:04","created_at":"2014-02-05 09:08:06.73429","updated_at":"2014-02-06 03:36:04.28132","publish_name":"blah","labels":["mylabel"],"text":"example text","publish_text":"example text","subject":"this is a subect","publish_subject":"this is a subect","from_email":"[email protected]","publish_from_email":"[email protected]","from_name":"Rich","publish_from_name":"Rich"}
но фрагмент jQuery этот ["code '] печатается в edit_div как" undefined "!
Что тут не так? Вся помощь была оценена. Спасибо.
Внутри обратного вызова вы $.each
, ваш код, похоже, хочет, чтобы this
было то же самое, что и data
, но на самом деле это то же самое, что и value
. Итак, если вы это сделаете:
$(document).ready(function(){
$( ".result" ).on( "click", "#edit_template", function() {
$.getJSON("/get_template_info?name=blah", function(data) {
$.each( data, function( key, value ) {
console.log(key + ":" + value);
});
});
});
});
Ты получишь:
slug:blah VM770:2
name:blah VM770:2
code:blah is the message
<p>and blah is how it is</p>
<p> I hope it gets better soon </p> VM770:2
publish_code:blah is the message
<p>and blah is how it is</p>
<p> I hope it gets better soon </p> VM770:2
published_at:2014-02-06 03:36:04 VM770:2
created_at:2014-02-05 09:08:06.73429 VM770:2
updated_at:2014-02-06 03:36:04.28132 VM770:2
publish_name:blah VM770:2
...
В вашем случае вы идете прямо к ключу "code", так что вы можете просто сделать:
$(document).ready(function(){
$( ".result" ).on( "click", "#edit_template", function() {
$.getJSON("/get_template_info?name=blah", function(data) {
var template_txt = '<p>' + data["code"] + '</p>';
$(".edit_div").append(template_txt);
});
});
});