我正在用Rails编写一个非常简单的todo应用程序。
查看:
h2 Your todos
ul#todo_list
= render @todos
hr
h4 Add new
= form_for(Todo.new, url: {action: 'create'}, remote: true) do |form|
= form.text_field :text
= form.submit 'Add'
CoffeeScript:
class Todo
constructor: () ->
@bindEvents()
bindEvents: () =>
console.log 'test1'
$(document).ajaxSuccess(@onAjaxSuccess)
onAjaxSuccess: (event, xhr, settings) ->
console.log 'test2'
$('#todo_list').append(xhr)
@isPresent: (element_id) ->
$("##{element_id}").length > 0
$(()->
new Todo if Todo.isPresent('todos')
)
当我创建一个新的待办事项时,test1
会打印在控制台中。我得到了200条正确的回应。不触发@onAjaxSuccess()
方法(未打印test2
)。为什么?
更新:
我刚刚读到jquery-ujs
会触发ajax:success
事件,所以我也尝试过:
bindEvents: () =>
console.log 'test1'
$('#new_todo').on('ajax:success', @onAjaxSuccess)
还是不起作用。
发布于 2016-03-11 03:06:36
问题是,没有触发'ajax:success'
,而是在xhr中返回html元素的'ajax:error.'
,jQuery试图将其解析为JSON (提示:绑定到'ajax:complete'
,并查看您得到了哪些错误)。
解决方案-更改表单的数据类型:
= form_for(Todo.new, url: {action: 'create'}, remote: true, html: { data: {type: :html} }) do |form|
= form.text_field :text
= form.submit 'Add'
发布于 2016-03-08 17:51:17
这个
@onAjaxSuccess: (event, xhr, settings) ->
应该是
onAjaxSuccess: (event, xhr, settings) ->
以便将其添加到prototype
中,并且可以使用this
进行访问。
发布于 2016-03-08 17:56:01
注意,还没有尝试过coffeescript
。
ajax请求是在javascript
上提出的吗?
.ajaxSuccess()
的第二个参数是jqXHR
对象。当将对象作为参数传递时,append()
似乎不会抛出错误,但不会将对象作为字符串附加到元素中。
var obj = {"abc":"123"};
$("body").append(obj);
如果ajax请求是由在form
提交的form.submit
?发出的,那么您应该能够使用$("#todo_list").append(xhr.responseText)
将ajax请求的响应附加到元素。
https://stackoverflow.com/questions/35881402
复制相似问题