我正在让用户触发(jquery click)ajax调用来加载额外的数据来填充网页,构建html的正确方法是什么:我应该在rails控制器中生成html并只返回html数据,还是应该返回JSON并在ajax函数中构建它?还是有一些更好的方法可以在 Rails 中进行 ajax 调用?
下面是目前的 countries.html.haml 代码(控制器中生成的 html 数据):
$('#tab li').click( function(){
$('#tab li').removeClass('active');
$(this).addClass('active');
var first_l = $(this).attr("id")
$.ajax({
url: "/countries/get_flags",
type: "GET",
data: {first_letter: first_l},
complete: function() {
// called when complete
},
success: function(data) {
// called when succesful
$('#countries_container').html("");
$('#countries_container').append(data);
},
error: function(xhr,status,error) {
// called when error
}
});
});
和控制器:
def get_flags
@html = ""
@fetched_countries = Country.all( :conditions => "name like '#{params[:first_letter]}%'")
i = 1
@html = "<div class='row country-row'>"
@fetched_countries.each do |country|
if i % 5 == 0
@html += "<div class='row country-row'>"
i = 1
end
@html += "<div class='span3 '>"
@html += "<div class='country-name'>#{country.name}</div>"
@html += "<div class='country-image thumbnail'><img alt='#{country.id.to_s}' src='/assets/countries/x100/#{country.id.to_s}.png' /></div></div>"
if i % 4 == 0
@html += "</div>"
end
i = i + 1
end
render :text => @html
end