【问题标题】:Add Product Options to Cart via AJAX and <form> | Opencart通过 AJAX 和 <form> | 将产品选项添加到购物车打开购物车
【发布时间】:2014-07-09 17:10:23
【问题描述】:

这是我在这里的第一个问题,因此我们将不胜感激。我找到了大量相关信息,但没有一个完全符合要求。

我正在尝试通过 HTML 表单和 AJAX 将具有各种选项的产品添加到购物车中。添加产品本身是第一个障碍,但现在看起来有点空洞的胜利。

我的表单如下所示:(列表中有更多产品,但我已编辑以节省空间)

<form action="http://[site_url].com/index.php?route=checkout/cart/add/" id="quickQuoteForm" method="post">
<h3>Select your course</h3>
<div class="quickPriceRow1 row1">
  <label>Choose a course</label>
  <select class="quickPriceSelect" name="product_id" rel="1">
    <option selected="selected" value="">Please choose...</option>
    <option name="product_id" value="50">Intensive General English - 15 hours per week</option>
    <option name="product_id" value="51">Intensive General English Course + Consolidation English/Exam Preparation Workshops (20 hours per week)</option>
  </select>

然后,包含在相同的表单中,我有这样的产品选项:

<label>Choose a start date</label>
<select name="start_date" class="quickPriceSelect2" rel="2" id="start_date">
    <option value="" selected="selected">Please choose...</option>

    <option name="option[5]" value="49">Monday July 28</option>
    <option name="option[5]" value="50">Monday August 04</option>
    <option name="option[5]" value="51">Monday August 11</option>
    <option name="option[5]" value="52">Monday August 18</option>
          etc...
 </select>

现在,我不是 100% 我的“name=...”是正确的,但我已经尝试了 'name="option[5]"' 和 'name="option_id[5]" '没有变化。我从 'option_description' 表和 'option_id' 列中获取 [5] 以及从 'option_value_description' 表和 'option_value_id' 列中获取的 value="50"。

感谢这个帖子 How do I add a product to OpenCart from an external site?(和一些小修修补补)我已经将产品添加到购物车中没有问题,但选项完全难倒我。

我的 jQuery 是:

$(document).ready(function() {
    $('#quickQuoteForm button').click(function(e) {
        e.preventDefault(); // prevent the form from submitting

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://[site_url].com/index.php?route=checkout/cart/add/',
            data: 'product_id=' + $('.quickPriceSelect').val() + '&quantity=1' + '&product_option_id=' + $('.quickPriceSelect2').val() + '&product_option_id=' + $('.quickPriceSelect3').val(),
            success: function(json) {
                window.location = 'http://[site_url].com/index.php?route=checkout/cart';
            }
        });
    });
});

如果有人能指出我正确的方向,那将是一个巨大的帮助,谢谢。

## 更新##

好的,所以我不再继续使用它,但我已经更改了我的 JS 以匹配我在 product.tpl 文件中找到的内容(默认和我正在使用的主题;Acceptus)。我现在有:

<script>
$('#button-cart').bind('click', function() {
    $.ajax({
        url: 'index.php?route=checkout/cart/add',
        type: 'post',
        data: $('select[name="product_id"], select[name="option[5]"], select[name="option[13]"]'),
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, information, .error').remove();

            if (json['error']) {
            if (json['error']['option']) {
                for (i in json['error']['option']) {
                    $('#option-' + i).after('<span class="error">' + json['error']['option'][i] +     </span>');
            }
        }
    } 

    if (json['success']) {
        $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/acceptus/image/icons/remove/close.png" alt="" class="close" /></div>');

        $('.success').fadeIn('slow');

        $('#cart-total').html(json['total']);

        $('html, body').animate({ scrollTop: 0 }, 'slow'); 
    }   

        if (json['success']) {
            window.location = 'http://studioamanchester.com/index.php?route=checkout/cart';
        }
    }
});
});
</script>'

同样,它正在添加产品,但没有任何选项。我已经尝试过默认主题并在本地安装了站点以对其进行测试,但仍然没有。还有什么可以尝试的吗?

【问题讨论】:

  • 当我实现opencart的时候,这已经是一个特性了。你用的是什么版本?购物车在线吗,可以发个链接吗?
  • 抱歉,它位于:studioamanchester.com,位于“BOOK”下方。此外,它仅适用于英文版。谢谢
  • 我不觉得你有问题,因为 这已经在 OpenCart 中实现,因为版本 1.3.x(当我第一次来到 OpenCart 时,这是 7 年前公平的!)。如果它在您的安装中不起作用,您应该注意您最近可能安装的模块/扩展/主题,这可能会破坏这种默认行为。如果可能(并且默认主题不会因您的更改而损坏),请将主题改回默认主题(在管理中)并尝试将带有选项的产品添加到购物车。你应该看到它工作得很好。看到您在将产品添加到购物车时遇到困难,这很奇怪……

标签: php jquery ajax opencart


【解决方案1】:

如您所见,您将变量作为查询字符串发送,而您应该尝试将它们作为 POST 变量发送。这是服务希望您发送的内容:

Request URL:http://studioamanchester.com/index.php?route=checkout/cart/add/
Request Method:POST

Query String Parametersview sourceview URL encoded
route:checkout/cart/add/

Form Dataview sourceview URL encoded
product_id:51
quantity:1
product_option_id:56
product_option_id:95

试试这个(不确定这两个属性是否同名,但看看它是否有效):

$(document).ready(function() {
    $('#quickQuoteForm button').click(function(e) {
        e.preventDefault(); // prevent the form from submitting

        var obj = { 
            product_id : $('.quickPriceSelect').val(), 
            quantity : "1", 
            product_option_id : $('.quickPriceSelect2').val(), 
            product_option_id : $('.quickPriceSelect3').val() 
        };

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://[site_url].com/index.php?route=checkout/cart/add/',
            data: JSON.stringify(obj),
            success: function(json) {
                window.location = 'http://[site_url].com/index.php?route=checkout/cart';
            }
        });
    });
});

【讨论】:

  • 嗯,首先谢谢你,但恐怕我不会再继续下去了。我已经按原样尝试了您的答案,但现在没有继续进入购物车页面。它停留在“/index.php?route=checkout/cart/add/”上并显示成功消息。它正在添加产品,但由于总价格保持不变,未添加选项。我还尝试将数量 = '1' 更改为数量:'1',因为我遇到了语法错误。这将继续到购物车页面,但不会添加任何产品。如果您能看到我看不到的任何内容,我已将其与您答案中的代码一起保留。
  • @carrdarch 您的图书页面上的方法似乎正在发送product_id:52, start_date:57, course_length:97, submit:Book,这与预期的product_id:51, quantity:1, product_option_id:56, product_option_id:95 不同
【解决方案2】:

查看您的 JS 代码,我可以看到 AJAX 请求本身存在一些错误:

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'http://[site_url].com/index.php?route=checkout/cart/add/',
//                  there should be no slash at the end of route  ---^
        data: 'product_id=' + $('.quickPriceSelect').val() + '&quantity=1' + '&product_option_id=' + $('.quickPriceSelect2').val() + '&product_option_id=' + $('.quickPriceSelect3').val(),
// if you send more 'product_option_id' properties, all of them will be overwritten by the last value in the end...
        success: function(json) {
            window.location = 'http://[site_url].com/index.php?route=checkout/cart';
        }
    });

我们缺少您的控制器代码,但我们希望您没有更改它。在这种情况下,POST 数据完全不正确,因为购物车控制器需要在 option 数组中接收产品选项,其中 option_id 作为键,production_option_value 作为值。

请求应该包含这样的 POST 数据:

option[208]     test
option[209]     adsgsdadas
option[217]     3
option[219]     2011-02-20
option[220]     2011-02-20 22:25
option[221]     22:25
option[222]     
option[223][]   10
product_id      42
quantity        2

由于您正在完全更改发送到服务器的 POST,因此您认为这是不可能的,这是可以理解的。您现在应该专注于修复代码,以便它以这种方式发送 AJAX POST 请求,而不是重新发明轮子(从默认的 product.tpl 模板复制):

$.ajax({
    url: 'index.php?route=checkout/cart/add',
    type: 'post',
    data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
    dataType: 'json',
    success: function(json) {
        $('.success, .warning, .attention, information, .error').remove();

        if (json['error']) {
            if (json['error']['option']) {
                for (i in json['error']['option']) {
                    $('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
                }
            }
        } 

        if (json['success']) {
            $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

            $('.success').fadeIn('slow');

            $('#cart-total').html(json['total']);

            $('html, body').animate({ scrollTop: 0 }, 'slow'); 
        }   
    }
});

包含data 的行包含所有内容 - 只需在给定的div 中查找任何表单字段并将其打包为name:value 到POST(而选项的名称为option[&lt;option_id&gt;])。

【讨论】:

  • 你能检查一下我发布的更新的JS吗?看看我有没有遗漏什么?\
  • 您是否也更改了CheckoutCartController 或系统库Cart 中的一些代码?
  • 我已经做了,但现在已经用 1.5.6.1 的新副本替换了整个 Controller 目录。我保留了更改后的 Controller > Common > header.php,它将信息页面带入菜单。但这不能影响它吗?我尝试使用干净的 header.php 添加产品选项,没有区别。
  • 好的,现在安装一个全新的 OpenCart 并试用它。或者只是去 demo.opencart.com 并在那里尝试......
  • 好的,好的。所以我几乎可以正常工作,但认为我的新问题可能超出了这个问题的范围。我从 product.tpl 的底部复制了相关的 jQuery 并将其添加到 information.tpl 的底部,并且正在捕获数据并将其发送到购物车。成功!但是,看起来我在表单本身中传递了错误的 ID。查看产品页面上的选择选项,我得到每种产品的不同值。如果每个产品都有相同的选项,那么每个产品的选项 ID 是否应该保持不变?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2019-10-02
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 2012-06-09
相关资源
最近更新 更多