Ajax 使用 coffeescript 响应的空值

Empty values on Ajax response using coffeescript

我在咖啡脚本中有 ajax - 它将值发送到后端。在浏览器面板中,我可以看到里面有 json 的响应,但成功时 - 所有变量都是未定义的。有人可以帮忙吗?

这里是 ajax 的代码。

    $.post '/articles/' + id + '/comments',
  contentType: 'application/json'
  data: comment_params:
    commenter: commenter
    body: body
  success: (data, textStatus, jQxhr) ->
    console.log(textStatus)
    $('#comments').append JSON.stringify(data)
  dataType: 'json'

所有变量 data, textStatus, jxQhr 未定义。我怎样才能从这些变量中得到这个值?

您应该查看文档以了解您要执行的操作:

$.post

$.ajax

这是执行 post 的两种方法,但它们具有不同的方法签名。

就像评论中所说的那样,您在这里看到的是不同语法的混合,这对任何一个都无效。

在大多数情况下,它看起来像 $.ajax 签名,因此您可以像这样稍微更改它(请注意,我还修复了缩进 - 尝试在您 post 代码时做到这一点在一个问题中,因为它对像 coffeescript 这样的语言很重要):

# Note i'm using string interpolation, not concatenation
$.ajax "/articles/#{id}/comments",
  # add this key-val to determine the request type
  method: "POST"
  contentType: 'application/json'
  data: comment_params:
    commenter: commenter
    body: body
  success: (data, textStatus, jQxhr) ->
    console.log(textStatus)
    $('#comments').append JSON.stringify(data)
  dataType: 'json'