jquery file upload rails redirect

最后都变了- 提交于 2019-12-12 00:42:45

问题


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.

I am using javascript to submit the file:

return data.submit();

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)}";
    })

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?


EDIT

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 + '%');
}
});

and here is my controller:

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

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

Thankyou


回答1:


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}" })

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 })
  }
})

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) } }


来源:https://stackoverflow.com/questions/18078201/jquery-file-upload-rails-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!