簡體   English   中英

使用Ajax添加到Sylius中的購物車

[英]Using Ajax to add to cart in Sylius

我已經按照這里的教程進行操作並且能夠更改重定向路由。 但是我希望這完全由Ajax完成,並且購物車總額會自動更新。 但是我無法覆蓋sylius的供應商目錄中的javascript。 有沒有人設法僅使用Ajax做到這一點?

在添加到此處詳細說明的購物車之后,Ive按照Sylius食譜文檔更改了重定向。 創建的重定向類將返回新的重定向路由:

$newUrl = $this->router->generate('your_new_route_name', []); 
$event->setResponse(new RedirectResponse($newUrl));

Ajax已經用於添加到購物車,並且重定向隨后發生。 我嘗試更改此代碼以返回簡單的響應(“成功”,200)。

但是,這會在處理ajax請求的供應商目錄中的腳本中導致錯誤。

$.each(response.errors.errors, function (key, message) {
    validationMessage += message;
});

Uncaught TypeError: Cannot read property 'errors' of undefined
  at HTMLFormElement.onFailure (app.js:1363)
  at Object.fail (app.js:23)
  at i (app.js:2)
  at Object.fireWith [as rejectWith] (app.js:2)
  at app.js:23

該指南告訴我要在前端處理此問題,但不能完全確定如何在供應商目錄中訪問此腳本。 該腳本是位於ShopBundle中的sylus-add-to-cart.js。

親切的問候

亞倫

我通過將一些自定義路由添加到routing.yml文件來實現這一點。

sylius_shop_partial_cart_add_item_ajax:
    path: /add-item
    methods: [GET]
    defaults:
        _controller: sylius.controller.order_item:addAction
        _sylius:
            template: $template
            factory:
                method: createForProduct
                arguments: [expr:notFoundOnNull(service('sylius.repository.product').find($productId))]
            form:
                type: Sylius\Bundle\CoreBundle\Form\Type\Order\AddToCartType
                options:
                    product: expr:notFoundOnNull(service('sylius.repository.product').find($productId))

sylius_shop_ajax_cart_item_remove_ajax:
    path: /{id}/remove
    methods: [DELETE]
    defaults:
        _controller: sylius.controller.order_item:removeAction
        _format: json

然后,我添加了使用表單選擇器在Submit上創建ajax請求,並在前端處理響應。

希望這對任何人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM