dongzhou4727 2016-02-23 18:21
浏览 28
已采纳

在Javascript中访问控制器变量的最佳方法是什么?

Controller

In my controller, I have an array store in this variable $month_g

dd($month_g);

I got

array:12 [▼
  0 => array:2 [▼
    "up_bytes" => 277664452
    "down_bytes" => 198868462
  ]
  1 => array:2 [▼
    "up_bytes" => 0
    "down_bytes" => 0
  ]
  2 => array:2 [▶]
  3 => array:2 [▶]
  4 => array:2 [▶]
  5 => array:2 [▶]
  6 => array:2 [▶]
  7 => array:2 [▶]
  8 => array:2 [▶]
  9 => array:2 [▶]
  10 => array:2 [▶]
  11 => array:2 [▶]
]

return view('page.index', get_defined_vars());

I want to be able to access this variable in my JS/View.


View

index.blade.php

I've tried

@extends('layouts.internal.master')
@section('content')

..... // content in HTML

@stop

@section('pagescripts')
    <script>
        console.log('{{$month_g}}');
    </script> 
@stop

Result

I kept getting

htmlentities() expects parameter 1 to be string, array given

But console.log() is capable of printing out an array.


Questions

How do I console.log that out ? What did I miss here ?

What is the best way to access controller variables within Javascript ?

  • 写回答

2条回答 默认 最新

  • dtxob80644 2016-02-23 18:23
    关注

    If $month_g is a PHP array, you want to first convert it to JSON so that javascript can use it.

    <script>
    var month_g = <?php echo json_encode($month_g) ?>;
    
    console.log(month_g);
    </script>
    

    PHP's json_encode method is the safest way to output PHP variables to be javascript variables in general. Even if you think the variable is an integer or simple string, json_encode it anyway just to be safe.

    Side note, you can also use Laravel's way instead of PHP tags if you prefer. Just note you need to use {!! instead of {{ so that the output isn't escaped.

    <script>
    var month_g = {!! json_encode($month_g) !!};
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)