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

And*_*rew 5 ajax templates rendering ruby-on-rails partial

在我当前的rails应用程序中,我正在使用ajax上传器库,需要您使用json响应{success:true}以指示文件已成功上载.

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

respond_to do |format|
  format.html { redirect_to @resource, :notice => 'Created.' }
  format.js
end
Run Code Online (Sandbox Code Playgroud)

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

$('#resources').append('<%= escape_javascript( render '@resource' ) %>');
Run Code Online (Sandbox Code Playgroud)

这就是我过去做过像Ajax评论等的事情.现在,要使上传器工作我的respond_to块目前执行此操作:

format.js { render :json => { :success => true } }
Run Code Online (Sandbox Code Playgroud)

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

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

dan*_*ich 4

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

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

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

format.js do
  partial = render_to_string @resource
  render :json => { :success => true, :partial => partial }
end
Run Code Online (Sandbox Code Playgroud)

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

var uploader = new qq.FileUploader({
  element: document.getElementById('file-uploader'),
  action: '/upload',
  onComplete: function(id, fileName, responseJSON) {
    $('#resources').append(responseJSON.partial);
  }
}); 
Run Code Online (Sandbox Code Playgroud)