我正在使用引導彈出窗口構建通知功能。當用戶單擊通知時,它會通過 ajax 調用將該通知標記為已讀。在 ajax 成功時,我想用更新的版本替換彈出窗口的內容。這是我到目前為止所擁有的:$(document).ready(function(){ $("#notificationsBell").popover({ 'title' : $('.notifications-title-header').html(), 'html' : true, 'placement' : 'left', 'content' : $(".notifications-list").html() }); });$('#notificationsBell').off("click").on("click", function() { $("#notificationsBell").popover('toggle');})$(document).on("click", ".notif-popup-container", function() { // 1. get correct id for clicked notification var notifId = $(this).attr("id"); // 2. Update the notification to be read and show update $.post( "/notifications/read", { notif_id: notifId }, ).done(function(data) { $('#notifUnreadCount').html(data.unread_notifs); // 3. Replace html content of hidden div with updated notifications $('.notifications-list').html("<%= j (render partial: 'notifications/partials/test_partial') %>"); // 4. Set popover content to be that div's html var popover = $('#notificationsBell').data('bs.popover'); popover.config.content = $('.notifications-list').html();})# what is originally stored in the popover <div style="display:none" class="notifications-list"> <%= render 'notifications/partials/popover_notifications' %></div># _popover_notifications.html.erb# this is rendered twice, once above and once on ajax success<% unread_notifications = Notification.unread_count(current_user) %><% if unread_notifications.eql? 0 %> No notifications to display! You are up to date.<% else %> <% notifs = current_user.notifications.where(read_at: nil).order("created_at DESC") %> <% notifs.each do |notif| %> </div> <% end %><% end %>此內容通過部分顯示。然而,這就是問題出現的地方。雖然我期望ajax成功回調中的部分在ajax成功時渲染,但最近了解到部分的渲染首先由服務器完成(甚至在任何js運行之前),然后是結果被傳回 javascript。因此,兩個部分都在頁面加載時呈現,這意味著我無法再在 ajax 成功后通過部分渲染動態設置彈出窗口內容。我的問題是,有沒有辦法解決這個問題,讓我能夠動態渲染部分內容,而不是在頁面加載時將其填充到 js 中?或者如果沒有,可能是一種完全不同的方法——我對任何想法持開放態度。謝謝。
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
您可以像這樣從控制器中獲取部分內容:
class TestController < ApplicationController
? def render_partial
? ? notification_id = params[:notification_id]
? ? # Fetch notification data
? ? notification = Notification.find(notification_id)
? ? # Return partial with new notification data
? ? render partial: 'notifications/partials/test_partial', locals: {:notification => notification}
? end
end
然后附加?JS 中的響應:
$('.notifications-list').append(resp)
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消