我正在为我的 Laravel 应用程序设置一个相对基本的通知系统,并且已经能够生成并向某人显示通知。
我现在正在构建清除通知计数的功能,并已成功使用一些 jQuery 来完成此操作。我需要进一步获取正在显示的所有通知的 ID,以便我可以在 AJAX 调用中发送它们,以便我可以将它们标记为在数据库中看到的。
作为一个非常基本的复制和粘贴,我创建了一个 JSFiddle的功能。由于它缺少我的 CSS 文件和资源,它无法工作或看起来很像我最后的效果...
在 fiddle 中,通知有一个以 notification-id-X
开头的 id
,其中 X
是所显示通知的 ID和一个显示相同内容的 data-id
属性(我不确定这是否需要)。
从我的搜索看来,我想使用类似下面的内容来搜索以 notification-id-
开头的所有 id
:
var notifications = $('[id^="notification-id-"]');
在完成此操作以获取我找到的所有 ID 并将它们发送到我的 Laravel 应用程序的 AJAX 调用中之后,我只是不知道如何处理 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
}
});
关于javascript - 在 AJAX 调用中发送 DIV 元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837127/