dongtan6695 2015-10-21 16:13
浏览 569
已采纳

如何使用Blade传递PHP变量来遍历JavaScript代码

I am using chart.js to show some data, and everything was working fine when the code was this:

JavaScript/Blade

 var pieDataAssignments = [

                @for($i = 0;$i<count($name);$i++)

            {
                value: {!! count(array_filter($ass_c,create_function('$a','return $a=="'.$name[$i].'";')))!!},
                color: 'pink',
                highlight: "#eaa5a2",
                label: 'Subject'
            },

                @endfor

        ];

Then I thought it was working, which it was, and I thought to start customising the Pie Chart.

Firstly I tried inserting the value for each variable individually, e.g.

color: {!! $colour[$i] !!},
etc...

That just prevented the pie chart from appearing, which led me to ponder my failure..

I then tried to insert everything into the first Blade call, like so:

Blade

{!!'

{
    value:'.count(array_filter($ass_c,create_function('$a','return $a=="'.$name[$i].'";'))).',
    color: "'.$colour[$i].'",
    highlight: "#eaa5a2",
    label: "hi"
},

'!!}

But still, it did not show up.

How can I go about looping JavaScript code and passing php variables at the same time? I don't know what else to try and I can't find anything online apart from telling me to do exactly what I tried.

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • 啊啊啊小孔 2015-10-21 16:24
    关注

    I fixed the issue, the code I had was recreating the array inside it's own instance. The code that now works is the following:

    var pieDataAssignments = [
    
            @for($i = 0;$i<count($name);$i++)
    
            {!!'
    
            {
                value:'.count(array_filter($ass_c,create_function('$a','return $a=="'.$name[$i].'";'))).',
                color: "'.$colour[$i].'",
                highlight: "#eaa5a2",
                label: "'.$name[$i].'"
            },
    
            '!!}
    
    
    
            @endfor
    
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值