2016-04-27 88 views
0

我的代碼如下所述,除了它不僅將具有所選變體的變量產品添加到購物車中,還額外增加了相同數量的同一產品,是一個簡單的產品。在woocommerce中添加可變產品到帶有Ajax的購物車

element.on('click', 'button[type="submit"]', event => { 
    event.preventDefault(); 

    const quantity = parseInt(element.find('input[name="quantity"]').val(), 10) || 1; 
    const addToCartUrl = '/shopping-basket/?wc-ajax=add_to_cart'; 
    let xWWWFormUrlencodedData = `quantity=${quantity}`; 

    switch (scope.singleCopy.type) { 
     case 'variable': { 
      if (scope.selectedVariation) { 
       for (const attr of scope.selectedVariation.attributes) { 
        xWWWFormUrlencodedData += `&attribute_pa_${attr.slug}=${attr.option}`; 
       } 
       xWWWFormUrlencodedData += `&add-to-cart=${scope.singleCopy.id}`; 
       xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`; 
       xWWWFormUrlencodedData += `&variation_id=${scope.selectedVariation.id}`; 
      } 
      break; 
     } 
     case 'simple': { 
      xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`; 
      break; 
     } 
     default: { 
      console.error(`Unknown product type ${scope.singleCopy.type}.`); //eslint-disable-line no-console 
     } 
    } 

    $http.post(addToCartUrl, xWWWFormUrlencodedData, { 
     withCredentials: true, 
     headers: { 
      'Cache-Control': 'no-cache', 
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
      Pragma: 'no-cache' 
     } 
    }).success(result => { 
     if (result.error) { 
      console.warn('The product has been added to the cart despite that the result object indicates an error!'); 
      // TODO: handle error 
      return; 
     } 
     console.log('Success.', result); 
     $rootScope.$broadcast('/cart/update/add'); 
    }).catch(data => { 
     console.error(data); 
     // TODO: handle error 
    }); 

}); 

如果我不派product_id,只能在所變化的變量產品添加到購物車(太棒了!),但結果對象指示錯誤(沒有說明)。如果我然後導航到購物車頁面,我會在ui中收到另一條錯誤消息:「對不起,此產品無法購買。」

我想現在我嘗試了所有排列,設置變體id而不是產品ID關於參數,刪除和添加回參數等等。任何想法如何解決這個問題?

+0

派生的自定義端點我在這裏提交的問題插件作者後:https://github.com/woothemes/woocommerce /問題/ 10810 – borisdiakur

回答

相關問題