开发者

AJAX Request & Return

I'm creating a "new blog" form and I have a few photo upload fields in the form. Is there a way I can sen开发者_开发问答d the post request using AJAX, uploading the photo, and return the photos url to display on the "new blog" form? My back end is written in ruby on rails.

I hope that makes sense! Any help greatly appreciated it!

Thanks, Alex


Yes, but it's a little complicated. The problem is that you cannot send uploaded files via AJAX, BUT there is a straightforward workaround which most people use.

This is how it works: You upload the photo into an invisible iFrame. You set this iframe as the upload form's target, and the user will be able to submit the form without reloading the page.

Example:

<iframe id="upload"></iframe>
<%= form_for @photo, :html => { :multipart => true, :id => 'photo_upload_form', :target => 'upload' }, :url => photos_path do |f| %>
  <div class="field">
    <%= f.label :image, 'Upload Photo' %>
    <%= f.file_field :image %>
  </div>    
<% end %>

...and of course use CSS to hide the iFrame. I think I once had an issue with hiding the iFrame with display: none, so I would recommend moving it off-screen by using something like:

#upload { position: absolute; left: -10px; top: -10px; width: 1px; height: 1px; }

Finally, you can use JavaScript in the view which is rendered inside the hidden iFrame via window.parent, so this way you can actually display the uploaded image inside the upload form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜