2017-08-26 44 views
1

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

这里是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都未定义。我怎么能从这些变量中获得这个值?

+0

['$ .post'](http://api.jquery.com/jQuery.post/)称为'$ .POST(URL,数据,成功,的dataType)' **或**'$ .post(settings_object)',你不是在混合这两个调用约定吗?另外,您确定需要手动调用'JSON.stringify'而不是仅仅将一个对象传递给'data:'? –

+0

@ muistooshort我从表单数据中删除了JSON.stringify - 但仍为空值。 – FridmanChan

+0

但是你仍然在尝试混合调用'$ .post'的两种不同方式。 –

回答

1

你应该看看文档为你想要做什么:

$.post

$.ajax

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

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

在大多数情况下,它看起来像$.ajax签名,这样你就可以稍微改变它像这样(注意,我也定了压痕 - 尝试并获得这个权利,当你在一个问题发布代码,因为它是语言显著像的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'