【问题标题】:Ajaxify link so that it still accesses address on click but doesn't change pageAjaxify 链接,以便它仍然在点击时访问地址但不更改页面
【发布时间】:2017-06-08 14:42:36
【问题描述】:

我有一个从购物车中删除商品的链接,但当您单击该链接时,它会将您重定向到现在已删除商品的购物车。是否有可能使您仍然可以单击它并且它仍然可以执行其操作但它不会更改页面(即它不会将用户发送到购物车)?

注意:我正在 Shopify 上使用 Liquid

链接:

<a href="/cart/change?line={{ forloop.index }}&amp;quantity=0" class="cart__remove">
                <small>{{ 'cart.general.remove' | t }}</small>
</a>

【问题讨论】:

  • 是的,通过简单的 AJAX 请求就可以实现,但您能说明一下您尝试过什么吗?
  • @drip 我几乎什么都没试过,因为我知道并且可以使用的唯一 AJAX 是 jQuery .load() 函数。老实说,我不知道如何处理这个问题。
  • @opportunityr 你的页面中包含 jQuery 吗?
  • @GabyakaG.Petrioli 是的。

标签: javascript jquery html shopify liquid


【解决方案1】:

既然您已经包含了 jQuery,请尝试添加以下脚本

jQuery(function($){
  $(document).on('click', 'a.cart__remove', function(e){
     e.preventDefault();
     var url = this.href;
     $.get(url, function(html){
       // here you know that the page the link was pointing to has executed
       // you might need to reload your card or parse it from the html you get here
       // because the index of the cart items has changed after removing one of them
       // and because you also need to update your shown cart to hide/remove the item that was selected

     });
  });
});

【讨论】:

  • @opportunityr 如果您可以发布您自己的购物车的 html,我可以添加代码以从 html 中删除商品,并更新其余 remove 按钮的网址。
  • @opportunityr 好的。如果你在某个地方卡住了,请告诉我。
【解决方案2】:

您可以改用购物车 js 来让您的事情随心所欲地工作。这是shopify购物车js的详细信息-cart js Reference

最好的方法是通过 CartJS.removeItem 函数发送行项目编号。您还可以使用 removeItemById 按其 ID 删除购物车项目。

它提供了 cart.requestComplete 事件侦听器,您可以在其中编写代码以在删除商品请求完成后重新加载您的页面。

【讨论】:

  • 您能否重新检查您的主题是否已包含购物车 js。它必须在您的主题的资产文件夹中。如果您需要进一步的帮助 - cartjs.org/pages/guide
【解决方案3】:

是的,你可以做

AJAX 代表异步 JavaScript 和 XML。

顾名思义,就是用来处理异步数据传输的。

为此,

将 HTML 更改为

<a onclick="removeCart('id');" class=" cart__remove "> <!--id indicates id of item as mentioned in your url //-->
    <small>{{ 'cart.general.remove' | t }}</small>
</a>

然后添加 JavaScript 代码

function removeCart(){
  var url = "cart/change?&quantity=0&line="+id;
  xhr = new XMLHttpRequest();
  //create an XHR object constructor
  xhr.open("GET",url,true);
  xhr.onreadystatechange=function(){
    if(xhr.status==200 && xhr.readyState==4){
      //Will execute if the request is success
      //Show some message to user saying that the item is removed
      //for example
      alert("Item removed");
    }
  }
  xhr.send();
}

如果需要,您也可以使用 HTTP POST。

【讨论】:

    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 2021-06-18
    • 2016-10-27
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2013-05-29
    相关资源
    最近更新 更多