我正在与Laravel合作,并实施Google跟踪代码管理器。我正在通过事件将对象推入Google的数据层。

<a href="javascript:void(0)"  class="btn btn-default"  id="step1"
 onclick="dataLayer.push({
 @foreach(Cart::content() as $content)
@if($loop->first)
'id': '{{$content->rowId}}',
'affiliation':'Gazebo',
'revenue':'{{Cart::total()}}',
@endif
@endforeach
'transactionProductts':[
 @foreach(Cart::content() as $cart)
     {
      'sku': '{{$cart->id}}',
       'price': '{{$cart->subtotal}}',
      'name':'{{$cart->name}}'
    }
    @if($loop->iteration != $loop->last)
    ,
    @endif
  @endforeach
 })">Continue.</a>


呈现后,在页面源代码中看起来像这样

<a href="javascript:void(0)" class="btn btn-default" id="step1" onclick="dataLayer.push({
  "affiliation": "foo-bar",
  "id": "id1",
  "revenue": "146.96",
  "transactionProductts": [
    {
      "name": "Video1",
      "price": "2.99",
      "sku": "23409"
    },
    {
      "name": "Video2",
      "price": "3.99",
      "sku": "21598"
    },
    {
      "name": "Video 3",
      "price": "129.99",
      "sku": "23430"
    },
    {
      "name": "Mozart&#039;s Magic Flute Diaries ",
      "price": "2.99",
      "sku": "22370"
    }
  ]
})">Continue.</a>


我在想这是我最后的条件语句并添加逗号,因为当我没有逗号时它可以正常工作,但是我需要包装条件语句,以便它不会在数组末尾添加逗号,并且它给了我“意外的标识符”错误

任何帮助,不胜感激

最佳答案

首先构建json字符串,并修剪尾随逗号:

@php
$json = ''
foreach(Cart::content() as $idx => $content) {
    if ($idx === 0) {
        $json .= "id: ${content->rowId},";
        $json .= "affiliation:'Gazebo',";
        $json .= "revenue: " . Cart::total() . ",";
    }
}

$json .= 'transactionProductts:[';

foreach(Cart::content() as $cart) {
    $json .= "{sku: ${cart->id},";
    $json .= "price: ${cart->subtotal,";
    $json .= "name: ${cart->name}},";
}

$final = trim($json, ',') . ']';

@endphp


onclick="dataLayer.push({ {{ $final }} })"

关于javascript - 与Laravel一起运行的Javascript中的意外标识符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51016323/

10-12 12:31