Javascript Laravel 数组转 json 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28524231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:56:12  来源:igfitidea点击:

Laravel array to json format

javascriptphphtmllaravel

提问by MrSSS16

So I'm trying to convert a Laravel array into jsonso I can then manipulate it through javascript. Im not sure how this is achieved correctly. Here is the code, so far

所以我试图将 Laravel 数组转换为json这样我可以通过 javascript 操作它。我不确定这是如何正确实现的。这是代码,到目前为止

@foreach ($posts as $post)
<div class="row">
   <div class="col-md-8">
     <div class="row">
        <div class="col-md-8 tag">
            <h4><strong><a href="{{{ $post>postName }}}">#{{String::title($posts->postName) }}</a></strong></h4>
        </div>
     </div>
    <!-- ./ post title -->
   </div>    
</div>
<hr />
@endforeach


<script type="text/javascript">
   var data = "{{ ($posts) }}"; // ??
   console.log(data);
</script>

回答by Jimmy Bernljung

You could return an json_encoded array from the controller like so:

您可以像这样从控制器返回一个 json_encoded 数组:

public function index()
{
    $posts = Post::all();
    $json = json_encode($posts);
    return View::make('posts.index', compact('posts', 'json'));
}

Which you then can work on in your view like you'd like:

然后您可以按照自己的意愿在您的视图中进行处理:

<script type="text/javascript">
    var data = {{ $json }};
    console.log(data);
</script>

Also, if you have sensitive fields on your post model, you should exclude these in the model class to prevent them to show in your javascript inspector:

此外,如果您的帖子模型中有敏感字段,您应该在模型类中排除这些字段以防止它们显示在您的 javascript 检查器中:

class Post extends \Eloquent {
    ...

    protected $hidden = array(
    'id',
    'created_at',
    'updated_at'
    );

    ...
}

回答by Marwelln

Use Eloquents built in function toJsonto get your rows as json.

使用内置函数的 EloquentstoJson将您的行作为 json。

<script type="text/javascript">
   var data = "{{ $posts->toJson() }}";
   console.log(data);
</script>

If there's some fields you don't want to include, add the field to the hiddenproperty in your model as Jimmy mentioned.

如果您不想包含某些字段hidden,请按照Jimmy 提到的方法将该字段添加到模型中的属性

回答by JulianMorris

If you looking for "high-level" way to convert plain array to json, you can use laravel collections.

如果您正在寻找将普通数组转换为 json 的“高级”方法,您可以使用 laravel 集合。

collect(['a' => 1, 'b' => 2, 'c' => 3])->toJson();

回答by Zain

<script type="text/javascript">
   let data = @json($posts);
   console.log(data);
</script>

回答by Pavan Jiwnani

you don't need to do all that, just use the php inbuilt function json_encode

你不需要做所有这些,只需使用 php 内置函数 json_encode

$json = json_encode($posts);
    echo $json;

<script type="text/javascript">
   var data = "$json"; // ??
   console.log(data);
</script>