Rails:AJAX控制器JS没有触发

时间:2010-03-16 20:47:51

标签: jquery ruby-on-rails ajax

我的控制器的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语句,并将“编辑”代替敏感信息。

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

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


解决方案:感谢抖动让我直接了解了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(Uploadify)回调:

$(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 }

1 个答案:

答案 0 :(得分:2)

我看不到您使用任何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代码段,例如我想create.js.erb来创建/输出像这样的东西

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

回调中你需要做的就是

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