2017-08-26 56 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'