2008年7月19日星期六

ajax upload use jquery + respond-to-parent

Ajax upload is cool.If you want to imeplement this in rails and your js libraray happen to is jquery, I think jquery and respond-to-parent plugin will make it easy.Maybe this plugin of jquey is also a way, but it can't be easy to use for me.

First you need to install the plugin,
in rails2.1, you can
./script/plugin install
git://github.com/markcatley/responds_to_parent.git
or

cd vender/plugins
git clone git://github.com/markcatley/responds_to_parent.git
cd ../..

then in your views, you need a form

form method="post" action="/couples/1/albums/1/pictures.js" target="background-uploader" enctype="multipart/form-data" id="background-upload-form"
<%= file_field_tag "picture_data[]", :id => 'ajax_upload_file' %>

and an iframe

iframe width="1" height="1" name="background-uploader" src="about:blank" style="display:none;"

maybe you also need a "loading" to make your site better:

div id="loading" style="display: none;"
<%= image_tag 'loading.gif' %> 上传中...

look, the iframe's name is same as form's tagret,so you can target your file upload forms to a child IFRAME.

then in js file,we can just use few lines to handle this :
$('#ajax_upload_file').change(function(){
$("#background-upload-form").hide()
$('#loading').show() $("#background-upload-form").submit()
});
and in controller we can use respond-to-parent link this:
respond_to do |wants|
wants.js do
responds_to_parent do
render :text => "jsFunction"
end
end
end
That's all, so your browser will excute the js function that render in the controller.

is this awesome?

没有评论: