jQuery文件上传rails重定向 [英] jquery file upload rails redirect

查看:69
本文介绍了jQuery文件上传rails重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using jquery-file-upload to upload files.

文件上传完毕后,我想重定向到上传文档的编辑路径.

After files are finished uploading, i want to redirect to the edit path of the uploaded document.

我正在使用javascript提交文件:

I am using javascript to submit the file:

return data.submit();

文件上传完成后,如何尝试重定向到edit_document_path?

After the file has finished uploading, how can I redirect to the edit_document_path, i have tried the following code:

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

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

Is there a way I can store or return the ID (or even better the @document itself) of the uploaded document so I can redirect through js?

我的js直接位于html.haml文件中

I have my js directly in the html.haml file

%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响应似乎不起作用,我在做什么错了?

However, the JSON response does not seem to be working as the page does not redirect, what am I doing wrong?

谢谢

推荐答案

您需要考虑几件事.首先,您必须能够获取编辑操作的网址.如果您的js位于页面中而不是资产文件中,则应进行以下更改.

there's a couple of things you have to consider. First, you have to be able to get the url to the edit action. If your js is in the page and not in an asset file, the following change should work.

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

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

you also need to use <%= %> if you are using erb instead of #{...}. If this is in an asset file, you don't have access to instance variables so you have to rely on the response of the server. As an example, you can set the response to be json.

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

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

since you're using json.url above, it expects you to return the url in the json response so in your controller, add the following to the respond_to block

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

这篇关于jQuery文件上传rails重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆