我想以HTML格式打印返回的JSON对象中的元素。 ruby代码是:
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":"rich@pchme.com","publish_from_email":"rich@pchme.com","from_name":"Rich","publish_from_name":"Rich"}
但jQuery片段此[[code]]在edit_div中打印为“undefined”!
这家伙有什么不对?所有帮助赞赏。谢谢。
答案 0 :(得分:0)
在您提供给$.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
...
在你的情况下,你会直接找到“代码”键,所以你可以这样做:
$(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);
});
});
});