我有一個在視圖中運行良好的 ajax 呼叫,但我想在一個咖啡腳本中制作它,就在一個資料表呼叫中。代碼如下所示:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "<%= people_path(format: :json) %>",
dataType: "json",
success: function({data}) {
const user_ids = data.map(user => user.id)
$("#people-ids").html(user_ids.join());
}
});
});
我是 coffeescript 的新手,所以我需要一些幫助來完成映射部分的方法。我可以做到這一點:
ajax:
type: 'GET'
url: $('#people-datatable').data('source')
dataType: 'json'
success: ({data}) ->
我在 {data} 中獲得了 7 個物件,但我不知道如何像在 JS 中那樣繼續檢索它們的 ID。有人可以幫忙嗎?
uj5u.com熱心網友回復:
在map迭代器函式中,您需要將引數名稱括在括號中。Coffeescript 不支持 javascript 中允許的不帶括號的語法。
這將是模棱兩可的,因為它可以被解釋為使用引數執行的user => ...函式user=> ...
這應該有效:
$(document).ready ->
$.ajax
type: "GET",
url: "<%= people_path(format: :json) %>",
dataType: "json",
success: ({ data }) ->
user_ids = data.map (user) -> user.id
$("#people-ids").html user_ids.join()
在學習語法時,在http://coffeescript.org/#try中構建片段可能很有用:這樣您就可以立即看到它轉譯成的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510050.html
