Coffeescript not handling ajax:success
正如我上周在一个问题中提到的,我正在使用 @coreyward 的 Rails 3 中模态编辑窗口的出色演练。但是,我是 Coffeescript 的相对新手,而且我我遇到了应该在成功的 Ajax 响应上显示模式窗口的代码。这是相关函数(取自 Corey 的要点):
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$ ->
$modal = $(‘#modal’) $modal_close = $modal.find(‘.close’) $modal_container = $(‘#modal-container’) # Handle modal links with the data-remote attribute $(document).on ‘click’, ‘#modal .close’, -> |
我已经确定函数内的所有代码都有效;它只是永远不会被调用。我可以在 Chrome 网络面板中看到 Ajax 查询,并验证它是否返回了正确的响应。
我简化了代码以在 ajax:success 事件上弹出警报:
1
2 |
$(document).on ‘ajax:success’, () ->
alert(‘Ajax success event!’) |
…什么也没有。所以我认为 `ajax:success\\’ 事件永远不会发生。
试图提取最简单的重复问题的代码,我使用以下代码设置了这个 jsFiddle:
Edit?
1
2 |
$(document).on ‘ajax:success’, () ->
alert(‘Ajax success event!’) |
?
…是的。没有什么。 jsFiddle Ajax 回显返回它应该返回的内容,但该函数永远不会被调用。所以我对 .on(‘ajax:success’) 做错了什么。 (这是与这个问题相反的问题,所以这个答案没有帮助。这个关于响应的 mime 类型的问题看起来很有希望,但没有解释为什么 jsFiddle 不起作用,因为这不会触及我的控制器。)它是什么?
ETA:我可能应该提到这里涉及的堆栈。掌心
- rails 3.2.8
- jquery-rails 2.1.3
- …这意味着 jQuery 1.8.2
好的,知道了。我需要进行两项更改:
- 首先,正如这个答案所建议的,我需要在响应中返回一个 text/json MIME 类型。我之前的操作是这样的:
1
2 3 4 5 6 |
def edit
respond_to do |format| format.js format.html end end |
为了得到 text/json 的响应,我总结了这个:
1
2 3 4 5 6 |
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 以实际将标记放入模态:
1
|
.html(data.html) // instead of .html(data)
|
来源:https://www.codenong.com/13362648/