Open yukina210 opened 2 months ago
いいねスクリプト
document.addEventListener("turbo:load", function() {
document.querySelectorAll('.like-icon').forEach(function(icon) {
icon.addEventListener('click', function(event) {
event.preventDefault();
const url = this.dataset.url;
const method = this.dataset.method;
fetch(url, {
method: method.toUpperCase(),
headers: {
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
this.classList.toggle('liked');
this.dataset.url = data.new_url;
this.dataset.method = data.new_method;
this.nextElementSibling.textContent = data.likes_count;
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
});
});
});