通过AJAX将收藏夹数组发送到PHP视图时出现问题


Problems sending array of favorites to a view in PHP via AJAX

我想知道将这个收藏夹数组发送到php的最佳方式,我试图使用ajax,但我一直收到403禁止的错误。这条路是正确的,我在这里一定做错了什么,任何帮助都将不胜感激。

$(function(){
    var favorite = localStorage.getItem( 'favorite' );
    if (favorite  !== null){
        favorite = JSON.parse(favorite) || [];
    }
    $('.favorites' ).each(function() {
        var petid = $(this).attr('data-petid');
        if(favorite.indexOf(petid) !== -1){
            $(this).css('background-image', 'url(../assets/img/heart-red.svg)');
            $(this).css('background-color', '#fefefe');
        }
    });
     // This function changes the color of the heart on the landing page and stores the values into local storage
    $(".favorites").click(function() {
       var favorite = localStorage.getItem( 'favorite' );
       var petid = $(this).attr('data-petid');
       var index;
       favorite = JSON.parse(favorite) || [];
       if ((index = favorite.indexOf(petid)) === -1) {
          favorite.push(petid);
          $(this).css('background-image', 'url(../assets/img/heart-red.svg)');
          $(this).css('background-color', '#fefefe');
       }else {
          $(this).css('background-image', 'url(../assets/img/heart-full.svg)');
          $(this).css('background-color', '#25aae3');
          favorite.splice(index, 1);
       }
       localStorage.setItem('favorite', JSON.stringify(favorite) );
       $.ajax({
          type: "POST",
          url: '/petlist/fuel/app/views/site/favorites.php',
          data: favorite,
          success: function(response){
            console.log(response);
          }
      });
    });
 });

对于Fuel中的ajax调用,请使用扩展controller_Rest 的控制器

您的ajax请求应该是这样的。
$.post('/petlist/fuel/app/views/site/favorites.php', { "favorite" : favorite }, function(data) { 
    console.log(data); 
});

然后在PHP中,您可以通过访问数据

print_r($_POST['favorite']);