2012-11-13 115 views
3

正如在上周的一个问题I mentioned,我与@coreywardexcellent walk-through在Rails的3模式编辑窗口工作然而,我与CoffeeScript的相对新手,和我有麻烦的代码应该显示在成功的Ajax响应上的模式窗口。这是相关的功能(从Corey's gist得出):的CoffeeScript不处理AJAX:成功

$ -> 
    $modal = $('#modal') 
    $modal_close = $modal.find('.close') 
    $modal_container = $('#modal-container') 

    # Handle modal links with the data-remote attribute 
    $(document).on 'ajax:success', 'a[data-remote]', (xhr, data, status) -> 
    $modal 
     .html(data) 
     .prepend($modal_close) 
     .css('top', $(window).scrollTop() + 40) 
     .show() 
    $modal_container.show(); 

    $(document).on 'click', '#modal .close', -> 
    $modal_container.hide() 
    $modal.hide() 
    false 

我已经确定函数内的所有代码工作;它只是永远不会被调用。我可以在Chrome网络面板中看到Ajax查询,并验证它是否会返回正确的响应。

我简化了代码,弹出一个警告上ajax:success事件:

$(document).on 'ajax:success',() -> 
    alert('Ajax success event!') 

...并没有什么。所以我认为`ajax:success'事件永远不会发生。

试图提取尽可能简单的代码复制的问题,我成立了this jsFiddle用下面的代码:

<a href="javascript:$.ajax('/echo/js/?delay=2&js=WHEEEEE!');" data-remote="true">Edit</a>​

$(document).on 'ajax:success',() -> 
    alert('Ajax success event!') 

...是啊。没有。 jsFiddle Ajax echo返回它应该的内容,但函数永远不会被调用。所以我在做错了.on('ajax:success')。 (这是与this question相反的问题,所以答案没有帮助,This question,关于MIME类型的响应,看起来很有前途,但并不能解释为什么jsFiddle不起作用,不要碰我的控制器。)它是什么? ETA:我应该提到这里涉及的堆栈。 捂脸

  • 的Rails 3.2.8
  • jQuery的轨道2.1.3
  • ...这意味着jQuery的1.8.2

回答

0

好,知道了。我需要做出两处修改:

  • 首先,this answer的建议,我需要被返回的响应text/json MIME类型。我以前的行动看上去是这样的:
def edit 
    respond_to do |format| 
     format.js 
     format.html 
    end 
    end 

要获得text/json响应我结束了与此:

def edit 
    respond_to do |format| 
     format.js { render :json => { :html => render_to_string('edit')}, :content_type => 'text/json' } 
     format.html 
    end 
    end 

这一变化引发ajax:success,因此跑了开模的功能。

  • 但是,因为响应的有效载荷是现在data.html而不仅仅是data,我需要调整的模式的modal.js.coffee真正把标记:
.html(data.html) // instead of .html(data)