简体   繁体   中英

How can I read information from a dataLayer, with javascript?

Good morning people of stackoverflow :)

I am working on an e-commerce website. One of our tracking partners requires the setup of a function named "csAdd". This function reads the customer cart and then uploads information.

What I would like to display for each line in the cart is information following this template :

myTag.csAdd('Sku1', 
  'Sku1Quantity',
  '', 
  'Sku1Quantity*ItemSinglePrice', 
  'ItemSinglePrice', 
'');

Same for Sku2, Sku3, etc.

The result* would be the following :

<script>
  myTag.csAdd('136340026', 
  '2',
  '', 
  '90', 
  '45', 
'');

  myTag.csAdd('774595138', 
  '1',
  '', 
  '49.99', 
  '49.99', 
'');

</script>

Please note that some single quotes are empty, this is not an error, our tracking script needs empty quotes where information is not present (for example item cost without VAT ).

* My problem is : I don't know how to tell javascript " for each line in the cart, please send me the information via csAdd "

The information needed is already displayed in a dataLayer so I think javascript "could" read this :

<script>
dataLayer = [{
  'pageTitle': 'BasketPage',
  'basketId': '2241121',
  'admincosts': '5,5',
  'basketTotal': '145.49',
   'basketProducts': [{
    'sku': '136340026',
    'name': 'Jean',
    'price': '90.00',
    'quantity': '2'
},{
    'sku': '774595138',
    'name': 'Jacket',
    'price': '49.99',
    'quantity': '1'
    }]
}];
</script>

But how can I proceed ? Thanks in advance for your time and help.

So you have an array dataLayer of json objects which contain property 'basketProducts' which is an array. You need two for loops (one to each array). In the second (nested) loop you call myTag.csAdd() method passing required properties values of each product in a basketProducts [bProd] array.

for (var i = 0; i < dataLayer.length; i++) {
    var bProd = dataLayer[i].basketProducts;
    for (var j = 0; j < bProd.length; j++) {
        myTag.csAdd(
                    bProd[j].sku,
                    bProd[j].quantity,
                    '',
                    bProd[j].quantity * bProd[j].price,
                    bProd[j].price,
                    ''
                    );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM