2012-03-12 89 views
1

我在我的控制器具有這樣的功能:使用Ajax和Ruby on Rails的

def showRecipeIngredients 
    ingredients = RecipeIngredient.where("recipe_id = ?", params[:id]).all 
    @html = "" 
    ingredients.each do |i| 
     @html = @html + "<p>#{Food.find_by_ndb_no(i.ndb_no).long_desc} - #{i.quantity} #{i.units}</p>" 
    end 


# value of @html: <p>Cheese, parmesan, grated - 6.0 cup</p><p>Cheese, port de salut - 8.0 cup, diced</p><p>Salad dressing, russian dressing, low calorie - 45.0 tablespoon</p> 

    result = @html 
    render(:json => result) 
end 

而且我在做這個AJAX調用:

$(".recipe_ids").click(function() { 

    var id = parseInt($(this).attr('id').substring(11)); 

    alert("THIS ID: " + id); 

    $.get("/recipes/showRecipeIngredients?id="+id, function(result) { 

//things get weird over here 
     var obj = jQuery.parseJSON(result); 
     var obj2 = <%= @html %> 

     $("#search_results").html(result); 
    } 

); 

這將通過控制器功能很好,但對於某種原因,我沒有回到我想要的來自呼叫的HTML。我什麼也沒得到。有人可以幫我嗎?

回答

2

如果要發送HTML在RESP然後相應

$.get("/recipes/showRecipeIngredients?id="+id, function(result) { 

     //no need to parse json if its not json 
     //var obj = jQuery.parseJSON(result); 
     var obj2 = <%= @html %> 

     $("#search_results").html(result); 
    },'html');//<-- set the dataType 
+0

啊哈設定的數據類型是沒有的伎倆!謝謝!真的沒有必要做一個嵌入的'<%= @html %>'在那裏? – lordmarinara 2012-03-12 07:36:06

+0

我真的不能說但顯然沒有必要 – Rafay 2012-03-12 07:39:54

+0

好的再次感謝。 – lordmarinara 2012-03-12 08:02:52