2013-07-28 107 views
0

我在Rails應用程序中遇到了一些麻煩與我的ajax請求。Rails ajax請求不刷新數據

我提出了一個請求,當我單擊時,我從鏈接中取出一些參數,然後我想刷新包含來自數據庫的圖像的部分。

,這裏是我的ajax

$.ajax({ 

     url:"gallery", 
     data: { pie :categoria}, 
     type: "GET", 
     async: true, 
     dataType: "script" 


    }); 

的事情是,在軌道外殼我爬PARAMS通過。 但它沒有做任何更改視圖。


我的外殼:

Started GET "/gallery?pie=VibPellizcables&_=1375047201412" for 127.0.0.1 at Sun Jul 28 18:33:21 -0300 2013 
Processing by GalleryController#pro as JS 
    Parameters: {"pie"=>"VibPellizcables", "_"=>"1375047201412"} 
    Product Load (0.1ms) SELECT `products`.* FROM `products` WHERE `products`.`pie` = 'VibPellizcables' 
    Rendered sexytoys/_algo.html.haml (0.1ms) 
Completed 200 OK in 1ms (Views: 0.6ms | ActiveRecord: 0.1ms) 

我想更新的部分包含圖片來自我的數據庫。

這是我想要更新的部分。

#miniDiv 

    %ul#miniRecuadro 
     - @products.each do |product| 
     %li.mini= image_tag product.pic.url(:thumb) 

我的控制器:

 def gallery 
     @products = Product.find(:all, :conditions => {:pie => params[:pie]}) 
     #render :partial => "algo" 
     flash[:notice] = "Mensaje ENVIADO >>" 
     respond_to do |format| 

      format.js {render :partial => 'algo', :conditions => {:pie => params[:pie]}} 
     # format.json { render :json => @products } 
     end 

回答

3

你要做的是更換或者響應或AJAX回調:

響應做更換

你需要渲染一個JS文件:

# app/controllers/gallery_controller.rb 
def pro 
    ... 
    respond_to do |format| 
    format.js # no render here 
    end 
    ... 
end 

# app/views/gallery/pro.js.erb 
$('#your-container').html('<%= j(render partial: 'algo')%>') 

我不確定這個路徑,如果這個路徑錯誤,應用程序會報錯,你會在瀏覽器控制檯看到這個,因爲這是AJAX。我不知道conditions選項是否支持在視圖中。

回調做更換

$.ajax({ 

    url:"gallery", 
    data: { pie :categoria}, 
    type: "GET", 
    async: true, 
    success: function(response){ 
     $('#your-container').html(response); 
    } 


}); 

注意我刪除dataType: 'script'在這裏,因爲你不想要執行的服務器響應。

在這種情況下,你可以與HTML你迴應迴應:

# gallery_controller.rb 
... 
    format.html {render :partial => 'algo', :conditions => {:pie => params[:pie]}} 
... 

注意我改變你的反應的格式,因爲你是渲染HTML。

快捷

最後,如果要加載在你的頁面中的容器內從你的服務器上的內容,你可以在load感興趣:

$('#your-container').load('gallery', { pie: categoria }); 
+0

我嘗試用「回調做替換」選項和工作非常適合我,非常感謝。我會稍後再試用其他選項 再次感謝你胡安 – yojuako