【问题标题】:Can't get jQuery's ajaxSuccess() to work无法让 jQuery 的 ajaxSuccess() 工作
【发布时间】:2016-06-23 05:25:58
【问题描述】:

我正在 Rails 中编写一个非常简单的待办事项应用程序。

查看:

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)

还是不行。

【问题讨论】:

  • 预期结果是什么?
  • @guest271314 预期的结果是在控制台打印'test2'。
  • 在问题js 处调用 ajax 请求吗?
  • @guest271314 是的,一个ajax请求是因为表单有data-remote=true属性,而rails的jquery-ujs在这里使用ajax。
  • 您是否检查过网络选项卡以确认是否发出请求?或者如果响应是错误消息?

标签: jquery ruby-on-rails ajax coffeescript


【解决方案1】:

@onAjaxSuccess: (event, xhr, settings) ->

应该是

onAjaxSuccess: (event, xhr, settings) ->

这样它就会被添加到prototype 并且可以通过this 访问

【讨论】:

    【解决方案2】:

    注意,没有试过coffeescript

    问题的javascript 是否发出了ajax 请求?

    .ajaxSuccess()的第二个参数是jqXHR对象。 append() 在将对象作为参数传递时似乎不会引发错误,但不会将对象作为字符串附加到元素。

    var obj = {"abc":"123"};
    $("body").append(obj);
    

    如果一个ajax请求是由formform.submit提交的?,你应该可以使用$("#todo_list").append(xhr.responseText)将ajax请求的响应附加到元素。

    【讨论】:

    • 发出了一个 ajax 请求 - 这是由 Rails 完成的。我得到了我想要的回应。我什至没有进入onAjaxSuccess 方法,所以问题与append 无关。
    • @onAjaxSuccess$(document).ajaxSuccess(@onAjaxSuccess) , bindEvents 之后定义是否重要?您是否尝试将 bindEvents 放在 @onAjaxSuccess: (event, xhr, settings) -> 之后?或者它们是独立的功能? form 是否在定义 $(document).ajaxSuccess(@onAjaxSuccess) 事件处理程序之前提交?
    【解决方案3】:

    问题是,不是'ajax:success' 被触发了,而是'ajax:error.' 在xhr 中我返回了html 元素,而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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多