Rails JS Response,呈现状态和模板?

时间:2012-03-07 01:13:42

标签: ruby-on-rails ajax templates rendering partial

在我当前的rails应用程序中,我正在使用ajax uploader库,要求您使用json {success:true}进行响应,以指示文件已成功上传。

在我的应用程序中,文件是图像,上传后我想将其添加到页面中。通常我会做类似的事情:

respond_to do |format|
  format.html { redirect_to @resource, :notice => 'Created.' }
  format.js
end

在上面的示例中,我的JS响应将呈现相应的模板,例如create.js.erb,可能会说... ...

$('#resources').append('<%= escape_javascript( render '@resource' ) %>');

这就是我过去做过像Ajax评论等的事情。现在,为了让上传者工作我的respond_to块目前正在执行此操作:

format.js { render :json => { :success => true } }

这使得上传器工作,但似乎阻止我像往常一样使用Ajax响应向页面添加渲染部分。

我的问题是,有没有办法实现这两种目标?如果没有,在成功创建成功创建对象后,如何填充页面?

1 个答案:

答案 0 :(得分:4)

您无法直接从控制器或使用视图模板执行此操作。看起来ajax uploader期望可以解析为JSON的响应,因此使用模板添加任何其他响应(这意味着不会执行format.js { render :json => { :success => true }})将不会将JSON作为响应主体发回。

查看插件的source,您可以看到您可以定义一个运行onComplete的方法,该方法将为您提供JSON响应。

这是未经测试的,但应该让你接近。所以,如果扩展您的JSON响应,如

format.js do
  partial = render_to_string @resource
  render :json => { :success => true, :partial => partial }
end

然后在您设置ajax上传器时在页面上的javascript中添加回调

var uploader = new qq.FileUploader({
  element: document.getElementById('file-uploader'),
  action: '/upload',
  onComplete: function(id, fileName, responseJSON) {
    $('#resources').append(responseJSON.partial);
  }
}); 
相关问题