Rails 3使用http而不是AJAX提交图像上传表单 [英] Rails 3 Image upload form submitting with http instead of AJAX

查看:132
本文介绍了Rails 3使用http而不是AJAX提交图像上传表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX而不是http来提交表单。
这是表格:

I am working on a form to submit it by AJAX instead of http. This is the form :

    <%= form_for(:image, :remote => true, :url => {:controller=> 'questions',:action => 'upload'},:multipart => true) do |f| %>

    <%= f.file_field :image, :onchange => "$(this).parents('form').submit();"  %>

    <% end %>

我设置了:remote =>上面是true 选项,并使用 onchange 事件提交表单。我在控制器中有以下代码:

I have set the :remote => true option above and submitting the form with an onchange event . I have the following code in controller :

def upload

     if request.xhr?
        @image = Image.new(params[:image])
        @image.save

            respond_to do |format|
                format.js { render :layout=>false }
           end
     else
           render :text => 'Request Wasnt AJAX'
     end
end

我的操作每次都会呈现文本,尽管设置了远程标记(即使在最终的HTML中它也能正确显示),但请求似乎不是AJAX样式。我无法弄清楚我在哪里出错了。我已经在FF和Chrome的最新浏览器版本中对其进行了测试,因此我认为这不是浏览器问题。有什么想法吗?

My action renders the text everytime , the request does not seem to be AJAX style despite the remote tag being set (it appears correctly even in the final HTML). I can't figure out where I am going wrong with this . I have tested it in the latest browser version of FF and Chrome , so I don't think it's a browser issue. Any ideas ?

更新:我做了一些调试尝试。问题在于文件字段,如果我用文本字段替换文件字段,请求是AJAX(其他一切保持相同)。但是对于文件字段,它总是发送非AJAX请求。

Update : I did some more debugging attempts . The issue is with the file field , if I replace the file field with text field , the request is AJAX (everything else remaining same) . But with a file field it always sends a non AJAX request.

注意:总体目标是通过AJAX请求上传图像,响应不呈现,没有HTML,没有重定向,没有重新加载页面。

推荐答案

通过安装Remotipart gem来实现它。要使用ajax表单提交上传图像文件,这是唯一的方法。在这里找到git: https://github.com/JangoSteve/remotipart

Got it to work by installing the Remotipart gem . To upload image files using ajax form submission , this is the only way . Find the git here :https://github.com/JangoSteve/remotipart

这篇关于Rails 3使用http而不是AJAX提交图像上传表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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