rest api 实现登录用户点赞

Published
2023-08-23
浏览次数 :  60

$('.like-btn').on('click',function(){

const post_id = $(this).attr('data-post-id');

const lastClickTime = localStorage.getItem(`likeTime_${post_id}`);

if (!lastClickTime || (Date.now() - lastClickTime) >= 24 * 60 * 60 * 1000) {

  localStorage.setItem(`likeTime_${post_id}`, Date.now()); // Store the current time 

  $.ajax({

  url:wproot.root + 'wp/v2/posts/' + post_id,
  method:'GET',
  success:(res) => {
    let likeCount = res.meta.likeCount || 0;
    likeCount++; 

    //update the likecount on the server 
    $.ajax({
        url:wproot.root + 'wp/v2/posts/' + post_id,
        method:'POST', 
        beforeSend: function ( xhr ) {
                xhr.setRequestHeader( 'X-WP-Nonce', wproot.nonce );
            },
        data:{
          'meta':{
            'likeCount':likeCount
          }

        },
        success:(res) => {
          console.log('Like count updated successfully:', res);
          
          $(this).html('<i class="fa-2x fa fa-heart"></i>');
          $('.like-count').text(res.meta.likeCount);

        },
        error:(err) => {
         console.log('Error updating like count:', err);
        }

        });
          },

          error: (err) => {
            console.log('Error fetching current like count:', err);
        }


});


} else {
        // Notify the user that they need to wait
        $(this).html('<i class="fa-2x fa fa-heart"></i>');
        alert("You can only like once every 24 hours.");
    }

//send ajax to increase the like field 
//
});

});

Top