在 AJAX 调用中发送 DIV 元素的 ID

Sending IDs of DIV elements in an AJAX call

本文关键字:DIV 元素 ID AJAX 调用      更新时间:2023-09-26

我正在为我的Laravel应用程序设置一个相对基本的通知系统,并且已经生成并向某人显示通知。

我现在正在通过构建功能来清除通知计数,并设法使用一些 jQuery 来做到这一点。我需要进一步执行此操作以获取正在显示的所有通知的 ID,以便我可以在 AJAX 调用中发送它们,以便我可以将它们标记为在数据库中看到。

作为一个非常基本的复制和粘贴,我创建了一个功能的JSFiddle。由于它缺少我的 CSS 文件和资源,它不起作用或看起来很像我最终的样子......

在小提琴中,通知有一个以notification-id-X开头的id,其中X是显示的通知的 id,以及显示相同的 data-id 属性(我不确定是否需要这样做)。

从我的搜索中,我似乎想使用如下所示的内容来搜索以notification-id-开头的所有id

var notifications = $('[id^="notification-id-"]');

完成此操作后,我只是无法弄清楚如何处理notifications对象以获取我找到的所有 ID,并在 AJAX 调用中发送它们,我的 Laravel 应用程序可以读取它们。

你的notifications变成了一个jQuery对象,它包含与该选择器匹配的所有元素。只需遍历这些元素并创建一个存储其 ID 的数组:

var notifications = $('[id^="notification-id-"]').map(function() {
    return this.id.slice(16);
}).get();

这将为您提供一个数组,其中包含变量 notifications 中的 ID。

要通过 AJAX 发送它们,请执行以下操作:

$.ajax({
    url: "my_server_script.php",
    method: "POST" // Or whatever you're using (GET, PUT, etc.)
    data: notifications // Let jQuery handle packing the data for you
    success: function(response) {
         // The data was sent successfully and the server has responded (may have failed server side)
    },
    error: function(xhr, textStatus, errorThrown) {
        // AJAX (sending data) failed
    },
    complete: function() {
        // Runs at the end (after success or error) and always runs
    }
});