![](/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.