使用.each使用AJAX按id删除所有项



是否有可能使用ajax从服务器批量删除项?我完全搞不懂。

我试图运行每个函数拉url id为我的服务器上的每个项目,然后把它插入到一个ajax删除类型调用。这对我来说是有意义的,但我仍然是编程新手,我觉得我可能还有很长的路要走。

任何关于这方面的见解都将是一个巨大的帮助。谢谢。

$('#delete-friends').on('click', function() {
  $.ajax({
    type: 'GET',
    url: 'http://rest.learncode.academy/api/johnbob/friends',
    success: function(friends) {
      var scratchFriend = $.each(friends, function(i, friend) {
        var friendID = (friend.id);
        console.log(friendID);
        $ajax({
          type: 'DELETE',
          url: 'http://rest.learncode.academy/api/johnbob/friends/'
          friendID ','
          success: function() {
            console.log('Friend Deleted Successfully!');
          }
        });
      });
    }
  });
});
#delete-friends {
  position: absolute;
  top: 10%;
  left: 70%;
  font-size: 20px;
  border-radius: 10px;
}
<div class="friendForm">
  <button id="delete-friends">Delete all of the friends?</button>
  <h4>Be a friend</h4>
  <p>Name:
    <input type='text' id='name'>
  </p>
  <p>Age:
    <input type='text' id='age'>
  </p>
  <button id="add-friend">Join us Friend</button>
</div>

我认为最好发送一个朋友id数组到后端-你只需要稍微调整一下后端:

$('#delete-friends').on('click', function() {
  $.ajax({
    type: 'GET',
    url: 'http://rest.learncode.academy/api/johnbob/friends',
    success: function(friends) {
      if (!friends) {
          return;
      }
      var friendIds = [];
      $.each(friends, function(i, friend) {
        friendIds.push(friend.id);   
      });
      $ajax({
          type: 'POST',
          url: 'http://rest.learncode.academy/api/johnbob/friends/'
          data: {
            friendIds: friendIds
          },
          success: function() {
            console.log('Friend Deleted Successfully!');
          }
      });
    }
  });
});

或者更好-创建一个delete方法,它将获取一个用户并删除他的所有朋友:

    $('#delete-friends').on('click', function() {
      $.ajax({
        type: 'POST',
        url: 'http://rest.learncode.academy/api/delete/friends',
        data: {
            user: 'johnbob'
        },
        success: function(data) {
          if (!data) {
              return;
          }
          console.log(data);
        }
      });
    });

但是我猜你正在使用http://rest.learncode.academy/API,所以你不能真正改变后端。

从我在learncode的文档中看到的,你可以在url中添加朋友的id来删除它。这应该能奏效:

        // -- SAME CODE FROM ANSWER --
        $ajax({
          type: 'DELETE',
          url: 'http://rest.learncode.academy/api/johnbob/friends/' + friendID
          success: function() {
            console.log('Friend Deleted Successfully!');
          }
        });
        // -- SAME CODE FROM ANSWER --

通常服务器有一个批量删除功能,您可以在其中传递您想要删除的所有id。一个接一个地删除它们是有点多的流量,因为您发送到服务器的每个id/请求还发送有关请求的元信息,这将是冗余的。您可以通过发送所有id将此请求减少为一个。

最新更新