document.addEventListener('DOMContentLoaded', function() { // 加入购物车按钮点击事件 const addToCartBtn = document.querySelector('.btn-add-to-cart'); addToCartBtn.addEventListener('click', function() { // 请求加入购物车接口 Rails.ajax({ url: '/cart/add', type: 'POST', data: { sku_id: document.querySelector('label.active input[name=skus]').value, amount: document.querySelector('.cart_amount input').value, }, success: function() { // 请求成功执行此回调 alert('加入购物车成功', '', 'success'); }, error: function(xhr) { // 请求失败执行此回调 if (xhr.status === 401) { // http 状态码为 401 代表用户未登陆 alert('请先登录', '', 'error'); } else if (xhr.status === 422) { // http 状态码为 422 代表用户输入校验失败 var html = '

'; Object.values(xhr.responseJSON.errors).forEach(function(errors) { errors.forEach(function(error) { html += error + '
'; }) }); html += '
'; alert({content: $(html)[0], icon: 'error'}) } else { // 其他情况应该是系统挂了 alert('系统错误', '', 'error'); } } }); }); });

Rails.ajax 加入购物车按钮实现代码

原文地址: https://www.cveoy.top/t/topic/pXLA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录