我正在尝试向我的 Rails 应用添加通知。基本上我从一个 JSON 端点获取它们,我尝试使用一些 Coffeescript Here's the JSON array 获取它们并将它们附加到我的 html 中。 .问题出在 handleSuccess 方法中,我收到 Uncaught ReferenceError ,通知未定义
notifications.js.coffee
class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
@setup() if @notifications.length > 0
setup: ->
$.ajax(
url: "/notifications.json"
dataType: "JSON"
method: "GET"
success: @handleSuccess
)
handleSuccess: (data) =>
console.log(data)
items = $.map data, (notification) ->
"<a class='dropdown-item' href='#{notification.url}'>#
{notification.action} #{notification.notifiable.type}</a>"
jQuery ->
new Notifications
我从 localhost:3000/notifications.json 得到了什么
[{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"}, {"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"},{"actor":"emanuelcoen""action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type ":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"}, "url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url": "/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"}]
最佳答案
您传递给 $.map
的函数中存在缩进错误。它下面的字符串必须缩进,否则它会假定您正在传递一个空函数来映射,并且它后面的行会引发错误,因为 notification
未定义。
handleSuccess: (data) =>
console.log(data)
items = $.map data, (notification) ->
"<a class='dropdown-item' href=''>#{notification.actor}</a>"
更新
关于您关于通知未显示在页面上的评论 - 您没有调用任何代码来将您生成的 html 字符串添加到 DOM。你可以使用 $.append为此。
handleSuccess: (data) =>
console.log(data)
for notification in data
@notifications.append(
"<a class='dropdown-item' href=''>#{notification.actor}</a>")
不需要在通知数组上使用 $.map
,因为我们只是在另一个循环中渲染它们,所以我用一个 Coffeescript 理解替换了它。
关于javascript - Uncaught ReferenceError ,通知未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183528/