【问题标题】:jquery file upload rails redirectjquery文件上传rails重定向
【发布时间】:2013-08-06 10:54:35
【问题描述】:

我正在使用 jquery-file-upload 上传文件。

文件上传完成后,我想重定向到上传文件的编辑路径。

我正在使用javascript提交文件:

return data.submit();

文件上传完成后,如何重定向到edit_document_path,我尝试了以下代码:

$('#fileupload')
    .bind('fileuploadstop', function (e, data) {
        window.location.href = "#{edit_document_path(@document)}";
    })

有没有一种方法可以存储或返回上传文档的 ID(甚至更好的是 @document 本身),以便我可以通过 js 重定向?


编辑

我的 js 直接在 html.haml 文件中

%script(type="text/javascript")
$('#new_document').fileupload({
dataType: 'json',

add: function (e, data) {
jqXHR = data.submit()
},

done: function (e, data) {
window.location = json.url
}, 

progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.bar').css('width', progress + '%');
}
});

这是我的控制器:

def upload
  @document = Document.new(params[:document])
  respond_to do |format|
    format.json { render json: { url: edit_document_path(@document) } }
  end
end

但是,由于页面没有重定向,JSON 响应似乎不起作用,我做错了什么?

谢谢你

【问题讨论】:

    标签: javascript ruby-on-rails redirect jquery-file-upload


    【解决方案1】:

    您需要考虑几件事情。首先,您必须能够获取编辑操作的 url。如果您的 js 在页面中而不是在资产文件中,则以下更改应该可以工作。

    jqXHR = data.submit()
      .complete(function() { window.location = "#{url here}" })
    

    如果您使用的是erb 而不是#{...},则还需要使用<%= %>。如果这是在资产文件中,则您无权访问实例变量,因此您必须依赖服务器的响应。例如,您可以将响应设置为json

    $('#fileupload').fileupload({
      dataType: 'json',
      add: function(json) {
       jqXHR = data.submit()
        .complete(function() { window.location = json.url })
      }
    })
    

    由于您在上面使用json.url,它希望您在 json 响应中返回 url,因此在您的控制器中,将以下内容添加到 respond_to

    format.json { render json: { url: edit_document_path(@document) } }
    

    【讨论】:

    • 非常感谢您的回复。你在“#{url here}”中有什么建议? “编辑文档路径(@document)”?
    • 答案是一样的。将添加选项更改为看起来像我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多