I'm using a JQuery-based file upload plugin to upload an image file directly to S3. The plugin works fine and the upload code, implemented in the model, is just peachy, too. My problem is with what happens after the file completes its quick journey.
The plugin accepts a callback, 'onLoad', which executes once the upload is complete. For the callback to work, all that's needed is a Javascript function which, 开发者_运维问答you know, does whatever comes next. Okay. What I'd like is for the callback to load a partial that would replace the upload form with a display of the image. So here's how I'm specifying the callback:
onLoad: function (evt, files, index, xhr, handler) {
(document).ready(function($) {
$('.container').html('<%= escape_javascript(render :partial => "pictures/picture_editor", :locals => { :picture => @picture }, :layout => false) %>')});
}
So -- what I don't want, of course, is for that 'render' tag to render prior to the callback, but that's exactly what's happening. The page loads and, immediately, I get an error because Rails is trying to render that tag, without waiting for the Javascript to execute or anything else -- Rails sees the tag in the view, bang, wants to render it. I've tried researching an answer and I feel like I must be missing something painfully obvious -- but how am I to load a partial from a jQuery callback if I can't specify the render tag in the view? What am I missing?
I apologize if the answer is very obvious.
A partial can't be rendered standalone (e.g. in an ajax response). One way that I think will fix it, assuming you still need the partial to be a partial (i.e. you need to render it as part of other pages), is:
- Create a
PicturesController#picture_editor
action that just renders the partial without a layout. - In the JavaScript event handler, load that action into the div using jQuery's 'load' function.
Something like this in PicturesController:
def picture_editor
@picture = Picture.find(params[:id])
render :partial => 'picture_editor', :picture => @picture :layout => false
end
and this in the JavaScript (in a .html.erb or .js.erb file so it will be processed by Ruby; not in raw .js):
$('.container').load('<%= url_for(:controller => 'Pictures', :action => 'picture_editor' %>')});
精彩评论