【问题标题】:get json data from just one product in shopify仅从 shopify 中的一种产品获取 json 数据
【发布时间】:2016-08-05 09:27:18
【问题描述】:

我想做什么:

当我在集合页面网格中单击产品时,我正在尝试使用 ajax 获取产品的标题等。

这是我的代码:

{% for product in collection.products %}

<div class="product">
 {% capture producturl %}{{ product.url }}{% endcapture %}
 <a class="ajax ajax{% increment ajaxno %}">
 PRODUCT IMAGE 
 </a> 
</div>


<script>
jQuery(function ($) { 

  $("a.ajax0").click(function(){
    jQuery.getJSON('{{ producturl }}.js', function(product) {
      console.log('The title of this product is ' + product.title);
    } );
  });

});
</script>

{% endfor%}

但是当我点击任何产品时,我会收到当前页面上所有产品的警报。 如何调整我的代码以仅获取我正在单击的产品的标题?

【问题讨论】:

    标签: json shopify liquid


    【解决方案1】:

    您可以在不使用 AJAX 的情况下做到这一点:

    {% for product in collection.products %}
      <div class="product">
       <a class="product-image" data-title="{{product.title}}">
        PRODUCT IMAGE 
       </a> 
      </div>
    {% endfor%}
    
    <script>
      jQuery(function($) { 
        $("a.product-image").click(function() {
          console.log($(this).data('title'));
        });
      });
    </script>
    

    如果出于某种原因您更喜欢使用 AJAX,这应该可以正常工作:

    {% for product in collection.products %}
      <div class="product">
       <a class="product-image" data-url="{{product.url}}">
        PRODUCT IMAGE 
       </a> 
      </div>
    {% endfor%}
    
    <script>
    jQuery(function($) {
      $("a.product-image").click(function(){
        var productUrl = $(this).data('url');
        jQuery.getJSON(productUrl + '.js', function(product) {
          console.log('The title of this product is ' + product.title);
        } );
      });
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多