javascript Ajax加入购物车(样品)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Ajax加入购物车(样品)相关的知识,希望对你有一定的参考价值。

1. Add cart.min.js to Vendors folder

2. Include cart.min.js in vendor.js

3. Include cartJS init in theme.js (right above first $(document).ready)

4. Add cartJS add to cart trigger to product.liquid

5. Add cartJS add to cart script to theme.js
<a class="sample-trigger" data-id="{% for variant in product.variants %}{% if variant.title contains 'Sample' %}{{ variant.id }}{% endif %}{% endfor %}">{{ section.settings.sample-cta }}</a>
/*!
 * cart.min.js
 */
// =require vendor/cart.min.js
// Step 3
if($('body').hasClass('template-product')){
  CartJS.init(cartjson);
}

// Step 5
$('.sample-trigger').click(function(){
  $('.cart-loading').show();
  var sample = $(this).attr('data-id');
  CartJS.removeItemById(sample);
  CartJS.addItem(sample, 1, {},
  {
    "success": function(data, textStatus, jqXHR) {
      $('.loading').hide();
      var currentCart = parseInt($('.cart-text').text());
      var updatedCart = currentCart + parseInt(1);
      $('.cart-text').text(updatedCart);
      $('.sample-confirmation').show();
    },
    "error": function(jqXHR, textStatus, errorThrown) {
      $('.loading').hide();
      $form.find('.confirmation-message span.message').text('Error: ' + errorThrown + '!').closest('.confirmation-message').addClass('visible');
    }
  });
});
// Cart.js
// version: 0.4.1
// author: Gavin Ballard
// license: MIT
(function(){var a,b,c,d,e,f,g=function(a,b){return function(){return a.apply(b,arguments)}};b=function(){function a(){this.update=g(this.update,this)}return a.prototype.update=function(a){var b,c,e;for(c in a)e=a[c],"items"!==c&&(this[c]=e);return this.items=function(){var c,e,f,g;for(f=a.items,g=[],c=0,e=f.length;e>c;c++)b=f[c],g.push(new d(b));return g}()},a}(),d=function(){function a(a){this.propertyArray=g(this.propertyArray,this),this.update=g(this.update,this),this.update(a)}return a.prototype.update=function(a){var b,d;for(b in a)d=a[b],"properties"!==b&&(this[b]=d);return this.properties=c.Utils.extend({},a.properties)},a.prototype.propertyArray=function(){var a,b,c,d;c=this.properties,d=[];for(a in c)b=c[a],d.push({name:a,value:b});return d},a}(),c={settings:{debug:!1,dataAPI:!0,requestBodyClass:null,rivetsModels:{},currency:null,moneyFormat:null,moneyWithCurrencyFormat:null,weightUnit:"g",weightPrecision:0},cart:new b},c.init=function(a,b){return null==b&&(b={}),c.configure(b),c.Utils.log("Initialising CartJS."),c.cart.update(a),c.settings.dataAPI&&(c.Utils.log('"dataAPI" setting is true, initialising Data API.'),c.Data.init()),c.settings.requestBodyClass&&(c.Utils.log('"requestBodyClass" set, adding event listeners.'),jQuery(document).on("cart.requestStarted",function(){return jQuery("body").addClass(c.settings.requestBodyClass)}),jQuery(document).on("cart.requestComplete",function(){return jQuery("body").removeClass(c.settings.requestBodyClass)})),c.Rivets.init(),jQuery(document).trigger("cart.ready",[c.cart])},c.configure=function(a){return null==a&&(a={}),c.Utils.extend(c.settings,a)},null==window.console&&(window.console={},window.console.log=function(){}),c.Utils={log:function(){return c.Utils.console(console.log,arguments)},error:function(){return c.Utils.console(console.error,arguments)},console:function(a,b){return c.settings.debug&&"undefined"!=typeof console&&null!==console?(b=Array.prototype.slice.call(b),b.unshift("[CartJS]:"),a.apply(console,b)):void 0},wrapKeys:function(a,b,c){var d,e,f;null==b&&(b="properties"),f={};for(d in a)e=a[d],f[""+b+"["+d+"]"]=null!=c?c:e;return f},unwrapKeys:function(a,b,c){var d,e,f,g;null==b&&(b="properties"),e={};for(d in a)g=a[d],f=d.replace(""+b+"[","").replace("]",""),e[f]=null!=c?c:g;return e},extend:function(a,b){var c,d;for(c in b)d=b[c],a[c]=d;return a},clone:function(a){var b,c;if(null==a||"object"!=typeof a)return a;c=new a.constructor;for(b in a)c[b]=clone(a[b]);return c},isArray:Array.isArray||function(a){return"[object Array]"==={}.toString.call(a)},ensureArray:function(a){return c.Utils.isArray(a)?a:null!=a?[a]:[]},formatMoney:function(a,b,d,e){var f,g;return null==e&&(e=""),e||(e=c.settings.currency),null!=window.Currency&&e!==c.settings.currency&&(a=Currency.convert(a,c.settings.currency,e),null!=(null!=(f=window.Currency)?f.moneyFormats:void 0)&&e in window.Currency.moneyFormats&&(b=window.Currency.moneyFormats[e][d])),null!=(null!=(g=window.Shopify)?g.formatMoney:void 0)?Shopify.formatMoney(a,b):a},getSizedImageUrl:function(a,b){var c,d;return null!=(null!=(c=window.Shopify)&&null!=(d=c.Image)?d.getSizedImageUrl:void 0)?a?Shopify.Image.getSizedImageUrl(a,b):Shopify.Image.getSizedImageUrl("https://cdn.shopify.com/s/images/admin/no-image-.gif",b).replace("-_","-"):a?a:"https://cdn.shopify.com/s/images/admin/no-image-large.gif"}},f=[],e=!1,c.Queue={add:function(a,b,d){var g;return null==d&&(d={}),g={url:a,data:b,type:d.type||"POST",dataType:d.dataType||"json",success:c.Utils.ensureArray(d.success),error:c.Utils.ensureArray(d.error),complete:c.Utils.ensureArray(d.complete)},d.updateCart&&g.success.push(c.cart.update),f.push(g),e?void 0:(jQuery(document).trigger("cart.requestStarted",[c.cart]),c.Queue.process())},process:function(){var a;return f.length?(e=!0,a=f.shift(),a.complete=c.Queue.process,jQuery.ajax(a)):(e=!1,void jQuery(document).trigger("cart.requestComplete",[c.cart]))}},c.Core={getCart:function(a){return null==a&&(a={}),a.type="GET",a.updateCart=!0,c.Queue.add("/cart.js",{},a)},addItem:function(a,b,d,e){var f;return null==b&&(b=1),null==d&&(d={}),null==e&&(e={}),f=c.Utils.wrapKeys(d),f.id=a,f.quantity=b,c.Queue.add("/cart/add.js",f,e),c.Core.getCart()},updateItem:function(a,b,d,e){var f;return null==d&&(d={}),null==e&&(e={}),f=c.Utils.wrapKeys(d),f.line=a,null!=b&&(f.quantity=b),e.updateCart=!0,c.Queue.add("/cart/change.js",f,e)},removeItem:function(a,b){return null==b&&(b={}),c.Core.updateItem(a,0,{},b)},updateItemById:function(a,b,d,e){var f;return null==d&&(d={}),null==e&&(e={}),f=c.Utils.wrapKeys(d),f.id=a,null!=b&&(f.quantity=b),e.updateCart=!0,c.Queue.add("/cart/change.js",f,e)},updateItemQuantitiesById:function(a,b){return null==a&&(a={}),null==b&&(b={}),b.updateCart=!0,c.Queue.add("/cart/update.js",{updates:a},b)},removeItemById:function(a,b){var d;return null==b&&(b={}),d={id:a,quantity:0},b.updateCart=!0,c.Queue.add("/cart/change.js",d,b)},clear:function(a){return null==a&&(a={}),a.updateCart=!0,c.Queue.add("/cart/clear.js",{},a)},getAttribute:function(a,b){return a in c.cart.attributes?c.cart.attributes[a]:b},setAttribute:function(a,b,d){var e;return null==d&&(d={}),e={},e[a]=b,c.Core.setAttributes(e,d)},getAttributes:function(){return c.cart.attributes},setAttributes:function(a,b){return null==a&&(a={}),null==b&&(b={}),b.updateCart=!0,c.Queue.add("/cart/update.js",c.Utils.wrapKeys(a,"attributes"),b)},clearAttributes:function(a){return null==a&&(a={}),a.updateCart=!0,c.Queue.add("/cart/update.js",c.Utils.wrapKeys(c.Core.getAttributes(),"attributes",""),a)},getNote:function(){return c.cart.note},setNote:function(a,b){return null==b&&(b={}),b.updateCart=!0,c.Queue.add("/cart/update.js",{note:a},b)}},a=null,c.Data={init:function(){return a=jQuery(document),c.Data.setEventListeners("on"),c.Data.render(null,c.cart)},destroy:function(){return c.Data.setEventListeners("off")},setEventListeners:function(b){return a[b]("click","[data-cart-add]",c.Data.add),a[b]("click","[data-cart-remove]",c.Data.remove),a[b]("click","[data-cart-remove-id]",c.Data.removeById),a[b]("click","[data-cart-update]",c.Data.update),a[b]("click","[data-cart-update-id]",c.Data.updateById),a[b]("click","[data-cart-clear]",c.Data.clear),a[b]("change","[data-cart-toggle]",c.Data.toggle),a[b]("change","[data-cart-toggle-attribute]",c.Data.toggleAttribute),a[b]("submit","[data-cart-submit]",c.Data.submit),a[b]("cart.requestComplete",c.Data.render)},add:function(a){var b;return a.preventDefault(),b=jQuery(this),c.Core.addItem(b.attr("data-cart-add"),b.attr("data-cart-quantity"))},remove:function(a){var b;return a.preventDefault(),b=jQuery(this),c.Core.removeItem(b.attr("data-cart-remove"))},removeById:function(a){var b;return a.preventDefault(),b=jQuery(this),c.Core.removeItemById(b.attr("data-cart-remove-id"))},update:function(a){var b;return a.preventDefault(),b=jQuery(this),c.Core.updateItem(b.attr("data-cart-update"),b.attr("data-cart-quantity"))},updateById:function(a){var b;return a.preventDefault(),b=jQuery(this),c.Core.updateItemById(b.attr("data-cart-update-id"),b.attr("data-cart-quantity"))},clear:function(a){return a.preventDefault(),c.Core.clear()},toggle:function(){var a,b;return a=jQuery(this),b=a.attr("data-cart-toggle"),a.is(":checked")?c.Core.addItem(b):c.Core.removeItemById(b)},toggleAttribute:function(){var a,b;return a=jQuery(this),b=a.attr("data-cart-toggle-attribute"),c.Core.setAttribute(b,a.is(":checked")?"Yes":"")},submit:function(a){var b,d,e,f;return a.preventDefault(),b=jQuery(this).serializeArray(),d=void 0,f=void 0,e={},jQuery.each(b,function(a,b){return"id"===b.name?d=b.value:"quantity"===b.name?f=b.value:b.name.match(/^properties\[\w+\]$/)?e[b.name]=b.value:void 0}),c.Core.addItem(d,f,c.Utils.unwrapKeys(e))},render:function(a,b){var d;return d={item_count:b.item_count,total_price:b.total_price,total_price_money:c.Utils.formatMoney(b.total_price,c.settings.moneyFormat,"money_format",null!=("undefined"!=typeof Currency&&null!==Currency?Currency.currentCurrency:void 0)?Currency.currentCurrency:void 0),total_price_money_with_currency:c.Utils.formatMoney(b.total_price,c.settings.moneyWithCurrencyFormat,"money_with_currency_format",null!=("undefined"!=typeof Currency&&null!==Currency?Currency.currentCurrency:void 0)?Currency.currentCurrency:void 0)},jQuery("[data-cart-render]").each(function(){var a;return a=jQuery(this),a.html(d[a.attr("data-cart-render")])})}},"rivets"in window?(c.Rivets={model:null,boundViews:[],init:function(){return c.Rivets.bindViews()},destroy:function(){return c.Rivets.unbindViews()},bindViews:function(){return c.Utils.log("Rivets.js is present, binding views."),c.Rivets.unbindViews(),c.Rivets.model=c.Utils.extend({cart:c.cart},c.settings.rivetsModels),null!=window.Currency&&(c.Rivets.model.Currency=window.Currency),jQuery("[data-cart-view]").each(function(){var a;return a=rivets.bind(jQuery(this),c.Rivets.model),c.Rivets.boundViews.push(a)})},unbindViews:function(){var a,b,d,e;for(e=c.Rivets.boundViews,b=0,d=e.length;d>b;b++)a=e[b],a.unbind();return c.Rivets.boundViews=[]}},rivets.formatters.eq=function(a,b){return a===b},rivets.formatters.includes=function(a,b){return a.indexOf(b)>=0},rivets.formatters.match=function(a,b,c){return a.match(new RegExp(b,c))},rivets.formatters.lt=function(a,b){return b>a},rivets.formatters.gt=function(a,b){return a>b},rivets.formatters.not=function(a){return!a},rivets.formatters.empty=function(a){return!a.length},rivets.formatters.plus=function(a,b){return parseInt(a)+parseInt(b)},rivets.formatters.minus=function(a,b){return parseInt(a)-parseInt(b)},rivets.formatters.times=function(a,b){return a*b},rivets.formatters.divided_by=function(a,b){return a/b},rivets.formatters.modulo=function(a,b){return a%b},rivets.formatters.prepend=function(a,b){return b+a},rivets.formatters.append=function(a,b){return a+b},rivets.formatters.slice=function(a,b,c){return a.slice(b,c)},rivets.formatters.pluralize=function(a,b,d){return null==d&&(d=b+"s"),c.Utils.isArray(a)&&(a=a.length),1===a?b:d},rivets.formatters.array_element=function(a,b){return a[b]},rivets.formatters.array_first=function(a){return a[0]},rivets.formatters.array_last=function(a){return a[a.length-1]},rivets.formatters.money=function(a,b){return c.Utils.formatMoney(a,c.settings.moneyFormat,"money_format",b)},rivets.formatters.money_with_currency=function(a,b){return c.Utils.formatMoney(a,c.settings.moneyWithCurrencyFormat,"money_with_currency_format",b)},rivets.formatters.weight=function(a){switch(c.settings.weightUnit){case"kg":return(a/1e3).toFixed(c.settings.weightPrecision);case"oz":return(.035274*a).toFixed(c.settings.weightPrecision);case"lb":return(.00220462*a).toFixed(c.settings.weightPrecision);default:return a.toFixed(c.settings.weightPrecision)}},rivets.formatters.weight_with_unit=function(a){return rivets.formatters.weight(a)+c.settings.weightUnit},rivets.formatters.product_image_size=function(a,b){return c.Utils.getSizedImageUrl(a,b)},rivets.formatters.moneyWithCurrency=rivets.formatters.money_with_currency,rivets.formatters.weightWithUnit=rivets.formatters.weight_with_unit,rivets.formatters.productImageSize=rivets.formatters.product_image_size):c.Rivets={init:function(){},destroy:function(){}},c.factory=function(a){return a.init=c.init,a.configure=c.configure,a.cart=c.cart,a.settings=c.settings,a.getCart=c.Core.getCart,a.addItem=c.Core.addItem,a.updateItem=c.Core.updateItem,a.updateItemById=c.Core.updateItemById,a.updateItemQuantitiesById=c.Core.updateItemQuantitiesById,a.removeItem=c.Core.removeItem,a.removeItemById=c.Core.removeItemById,a.clear=c.Core.clear,a.getAttribute=c.Core.getAttribute,a.setAttribute=c.Core.setAttribute,a.getAttributes=c.Core.getAttributes,a.setAttributes=c.Core.setAttributes,a.clearAttributes=c.Core.clearAttributes,a.getNote=c.Core.getNote,a.setNote=c.Core.setNote,a.render=c.Data.render},"object"==typeof exports?c.factory(exports):"function"==typeof define&&define.amd?define(["exports"],function(a){return c.factory(this.CartJS=a),a}):c.factory(this.CartJS={})}).call(this);

以上是关于javascript Ajax加入购物车(样品)的主要内容,如果未能解决你的问题,请参考以下文章

AJAX无刷新加入购物车(基本代码)

隐藏订阅价格和详细信息 WooCommerce 免费样品

在 Woocommerce 中将 ajax 添加到购物车事件后运行 javascript 代码

CSS3&JavaScript 仿京东加入购物车特效

Javascript中的抛物线 ~ 加入购物车小动画

基于产品总数的特定类别折扣