如何正确组合这些AJAX和jQuery函数?

时间:2018-11-21 18:28:39

标签: javascript jquery ajax

每当我单击此按钮时:

<a onclick="AddToWishList(@item.id)" id="swapHeart" class="btn btn-default swap">
     <span class="glyphicon glyphicon-heart-empty"></span>
</a>

每当调用AJAX函数时,我希望按钮使用jQuery更改状态

AJAX:

<script>
    function AddToWishList(item_id) {
        $.ajax({
            type: "POST",
            data: {
                itm_id: item_id
            },
            url: "/WishList/AddToWishList",
            success: function (e) {
                e.preventDefault();
            },
            error: function () {
                return "error";
            }
        });
    }
</script>

jQuery:

<script src="~/lib/jquery/dist/jquery.min.js">
</script>
<script>
    jQuery(function ($) {
        $('#swapHeart').on('click', function () {
            var $el = $(this),
                textNode = this.lastChild;
            $el.find('span').toggleClass('glyphicon-heart glyphicon-heart-empty');
            $el.toggleClass('swap');
        });
    });
</script>

所以我首先想到的是,我必须将这两个功能合并为一个功能。但是如何?因为该按钮首先处理AJAX函数,然后处理jQuery。

谢谢!

1 个答案:

答案 0 :(得分:1)

摆脱onclick,并将商品ID传递给数据属性。

<a id="swapHeart" data-item_id="@item.id" .... </a> 

然后在jQuery点击处理程序中执行所有操作

$('#swapHeart').on('click', function(e) {
  e.preventDefault();// calling this in success of ajax is too late
  var $el = $(this);

  $.ajax({
    type: "POST",
    data: {
      itm_id: $el.data('item_id')// from data attribute
    },
    url: "/WishList/AddToWishList",
    success: function(data) {
      // do something with or based on response data

      $el.find('span').toggleClass('glyphicon-heart glyphicon-heart-empty');
      $el.toggleClass('swap');
    },
    error: function() {
      console.log("ajax error");
    }
  });

});