【问题标题】:Rails: AJAX Controller JS not firingRails:AJAX 控制器 JS 未触发
【发布时间】:2010-03-16 20:47:51
【问题描述】:

我的控制器的 AJAX 功能之一出现问题。这是我所拥有的:

class PhotosController < ApplicationController
  # ...
  def create
    @photo = Photo.new(params[:photo])
    @photo.image_content_type = MIME::Types.type_for(@photo.image_file_name).to_s
    @photo.image_width = Paperclip::Geometry.from_file(params[:photo][:image]).width.to_i
    @photo.image_height = Paperclip::Geometry.from_file(params[:photo][:image]).height.to_i
    @photo.save!

    respond_to do |format|
      format.js
    end
  end
  # ...
end

这是通过此代码发送的POST 请求调用的:

$(function() {
  // add photos link
  $('a.add-photos-link').colorbox({
    overlayClose: false,
    onComplete: function() { wire_add_photo_modal(); }
  });

  function wire_add_photo_modal() {
    <% session_key = ActionController::Base.session_options[:key] %>
    $('#upload_photo').uploadify({
      uploader: '/swf/uploadify.swf',
      script: '/photos',
      cancelImg: '/images/buttons/cancel.png',
      buttonText: 'Upload Photo(s)',
      auto: true,
      queueID: 'queue',
      fileDataName: 'photo[image]',
      scriptData: {
        '<%= session_key %>': '<%= u cookies[session_key] %>',
        commit: 'Adding Photo',
        controller: 'photos',
        action: 'create',
        '_method': 'post',
        'photo[gallery_id]': $('#gallery_id').val(),
        'photo[user_id]': $('#user_id').val(),
        authenticity_token: encodeURIComponent('<%= u form_authenticity_token if protect_against_forgery? %>')
      },
      multi: true
    });
  }
});

最后,我的回复代码在app/views/photos/create.js.erb

alert('photo added!');

我的日志文件显示请求成功(照片已成功上传),甚至说它呈现了create 操作,但我从未收到警报。我的浏览器没有显示任何 javascript 错误。

这是来自上述POST 请求的请求提交后的日志:

Processing PhotosController#create (for 127.0.0.1 at 2010-03-16 14:35:33) [POST]
Parameters: {"Filename"=>"tumblr_kx74k06IuI1qzt6cxo1_400.jpg", "photo"=>{"user_id"=>"1", "image"=>#<File:/tmp/RackMultipart20100316-54303-7r2npu-0>}, "commit"=>"Adding Photo", "_edited_session"=>"edited", "folder"=>"/kakagiloon/", "authenticity_token"=>"edited", "action"=>"create", "_method"=>"post", "Upload"=>"Submit Query", "controller"=>"photos"}
[paperclip] Saving attachments.
[paperclip] saving /public/images/assets/kakagiloon/thumbnail/tumblr_kx74k06IuI1qzt6cxo1_400.jpg
[paperclip] saving /public/images/assets/kakagiloon/profile/tumblr_kx74k06IuI1qzt6cxo1_400.jpg
[paperclip] saving /public/images/assets/kakagiloon/original/tumblr_kx74k06IuI1qzt6cxo1_400.jpg
Rendering photos/create
Completed in 248ms (View: 1, DB: 6) | 200 OK [http://edited.local/photos]

注意:我编辑了所有的 SQL 语句,并用“edited”代替了敏感信息。

什么给了?为什么我没有收到我的alert();

如果您需要更多信息来帮助我解决此问题,请告诉我!谢谢。


解决方案:感谢 jitter 让我直接了解 Uploadify 的回调。

控制器:

class PhotosController < ApplicationController
  # ...
  def create
    @photo = Photo.new(params[:photo])
    @photo.image_content_type = MIME::Types.type_for(@photo.image_file_name).to_s
    @photo.image_width = Paperclip::Geometry.from_file(params[:photo][:image]).width.to_i
    @photo.image_height = Paperclip::Geometry.from_file(params[:photo][:image]).height.to_i
    @photo.save!

    respond_to do |format|
      format.js { render :layout => false }
    end
  end
  # ...
end

Javascript(上传)回调:

$(function() {
  // add photos link
  $('a.add-photos-link').colorbox({
    overlayClose: false,
    onComplete: function() { wire_add_photo_modal($(this).parent()); }
  });

  function wire_add_photo_modal($parent) {
    <% session_key = ActionController::Base.session_options[:key] %>
    $('#upload_photo').uploadify({
      uploader: '/swf/uploadify.swf',
      script: '/photos',
      cancelImg: '/images/buttons/cancel.png',
      buttonText: 'Upload Photo(s)',
      auto: true,
      queueID: 'queue',
      fileDataName: 'photo[image]',
      scriptData: {
        '<%= session_key %>': '<%= u cookies[session_key] %>',
        commit: 'Adding Photo',
        controller: 'photos',
        action: 'create',
        '_method': 'post',
        'photo[gallery_id]': $('#gallery_id').val(),
        'photo[user_id]': $('#user_id').val(),
        authenticity_token: encodeURIComponent('<%= u form_authenticity_token if protect_against_forgery? %>')
      },
      multi: true,
      onComplete: function(event, queueID, fileObj, response, data) { 
        $parent.find('.gallery-photos').append(response);
      }
    });
  }
});

create.js.haml(从 ERB 更改模板语言,因为我基本上只是返回 HTML 内容):

- if @photo.gallery.nil?
  =render :partial => 'photos/photo', :locals => { :photo => @photo, :rel => 'unsorted' }
- else
  = render :partial => 'photos/photo', :locals => { :photo => @photo, :rel => gallery.title }

【问题讨论】:

    标签: jquery ruby-on-rails ajax


    【解决方案1】:

    我看不到您使用任何 uploadify 的回调。因此,我猜它只是忽略了服务器作为响应发送的任何内容。如果您想将有意义的响应发送回您的 javascript,请尝试使用函数连接 onComplete 选项

    查看uploadify documentation了解更多信息

    我想你可以将app/views/photos/create.js.erb 更改为

    photo added!
    

    然后做

    $('#upload_photo').uploadify({
        ...
        onComplete: function(event, queueID, fileObj, response, data) {
            alert("Server said: "+response+" for file "+fileObj.name);
        }
        ...
    });
    

    如果您想将照片添加到页面,您可以让服务器返回适当的 html sn-p 例如我想 create.js.erb 来创建/输出这样的东西

    <img src="Xxx.jpg" width="..." height="..." />
    

    在回调中你需要做的就是

    onComplete: function(event, queueID, fileObj, response, data) {
        $("selectorforwheretheimageshouldbeinserted").append(response);
        return true;
    }
    

    【讨论】:

    • 警报只是作为演示;我实际上想将照片添加到页面上(AJAX 更新)。我无法使用 Uploadify 的回调来让它工作,因为它不知道 Rails 创建的新 @photo 对象,而 create.js.erb 是。但是,如果我让 Uploadify 的 OnComplete 返回 false,我会失去它很好的自动清除队列行为(默认情况下它的作用,开箱即用)。任何解决方法的想法?
    猜你喜欢
    • 2015-11-25
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多