【问题标题】:Unexpected Idenifier in Javascript running with Laravel使用 Laravel 运行的 Javascript 中出现意外的标识符
【发布时间】:2018-06-25 04:31:07
【问题描述】:

我正在与 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>

我认为这是我最后一个条件语句并添加逗号,因为当我没有逗号时它可以正常工作,但我需要在条件语句中换行,这样它就不会在末尾添加逗号数组,它给了我“意外的标识符”错误

非常感谢任何帮助

【问题讨论】:

标签: javascript php laravel object tags


【解决方案1】:

先构建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 }} })"

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2021-11-05
    相关资源
    最近更新 更多