数组转换为Javascript数组

数组转换为Javascript数组

本文介绍了将Laravel集合/数组转换为Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Laravel中的一个数组分配给一个JavaScript数组.我已经从我的 AppServiceProvider 中获得了数组,并用json_decode对其进行了编码,如下所示:

I would like to assign an array from Laravel to a JavaScript array. I have gotten the array from my AppServiceProvider and json_decoded it like:

View::composer('*', function($view)
{
   $users = Users::all();
   $view->with(compact(users );
}

然后我从javascript文件访问$ usersArray,例如:

I then access my $usersArray from my javascript file like:

  var dataSet = JSON.parse({!!$users !!});

但是我遇到以下错误;

I am however getting the following error;

jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)

推荐答案

由于在服务器端进行编码,因此需要在客户端进行解码,例如:

Since you're encoding it in the server side, you need to decode it in the client side like:

$chequesArray = Users::all()->toJson();

var dataSet = JSON.parse({!!json_encode($chequesArray)!!});

或者也可以使用"base64_encode"保存json格式,例如:

Or also Using "base64_encode" to conserve the json format like:

$chequesArray = base64_encode(Users::all()->toJson());

var dataSet = JSON.parse(atob('{{$chequesArray}}');

主要区别在于使用 {{}} {!!!!} ,第一个转义特殊字符,因此它将引号" 变为& quot ,然后JS将无法解析字符串(这就是为什么我们可以使用base64_encode保留格式的原因),第二个将保留格式并允许使用引号使JS部分能够简单地解析它.

The main difference comes from the use of {{ }} vs {!! !!}, the first one escapes the special chars so it will turn the quotes "" to &quot; then the JS will be unable to parse the string (that why we can use `base64_encode``to conserve the format), the second one will conserve the format and allow the quotes what gives the JS part the ability to parse it simply.

这篇关于将Laravel集合/数组转换为Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:51