gpt4 book ai didi

javascript - 与 Laravel 一起运行的 Javascript 中出现意外标识符

转载 作者:行者123 更新时间:2023-12-03 01:37:09 27 4
gpt4 key购买 nike

我正在与 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 字符串并 trim 尾随逗号:

@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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com