![](/img/trans.png)
[英]what is the best way to deal with ajax and generating html that is beyond prototyping
[英]What is the right way to deal with AJAX on Rails 4?
我認為您做對了。 您正在使用Rails的AJAX幫助程序,這是一個好習慣。 與使用AJAX的常規方法相比,此方法的一些優點:
我不知道您的項目有多復雜,所以不確定,但是也許您可以改進以減少部分文件。 例如,我注意到您同時具有刪除和銷毀操作。 Index , new和edit視圖可能不需要部分文件。 看來您也可以處理Json請求。 這也使視圖文件夾更大。
是的,對我來說真的也很糟糕。 但是,如果要使用javascript響應每種方法,則必須為每個方法創建js.erb
模板。
另一種方法是,您希望使用json而不是腳本進行響應。 您所有的ajax代碼都將保留在客戶端javascript中,並且將以json數據作為響應。
例如。 讓我們獲取特定區域的數據
$.ajax({
url: "/areas/23",
dataType: 'json',
method: 'get',
success: function(response){
//OPTION 1
//response will have all the data
//handle the value from the response object in displaying
//OPTION 2
//If you set dataType: 'html' you can receive html partial from server and make use of it directly
$("#show-area").html(response); //response will have content of _show.html.erb
},
error: function(error){
console.log(error); //Print errors if it breaks
}
});
#Controller
def show
respond_to do |format|
#OPTIONS 1
format.json { render json: @area.as_json }
#Or have a json.jbuilder partial if you want to send data selectively, ;) There is no escape from partials/templates
#OPTION 2
format.html { render partial: "areas/show" } # will render _show.html.erb
end
end
話雖如此,我認為這最終取決於個人喜好。 您的偏好會因不同的情況而異。 您可以根據情況選擇任何一種。 讓我知道是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.