简体   繁体   English

使用json_encode()将php数组转换为javascript

[英]php array to javascript using json_encode()

I have a php array $presentation, and I am trying to assign it to a JavasScript variable. 我有一个php数组$ presentation,我正试图将其分配给JavasScript变量。 when I use json_encode i got this value: 当我使用json_encode我得到这个值:

{"image":"\/ara\/web\/uploads\/images\/slide\/34.jpeg","sound":"\/ara\/web\/uploads\/images\/slide\/34.mpga","content":"sentence"}

you see the back and forward slashes? 你看到前后斜线了吗?

and this gets worst when I try to assign the variable to a javascript one: I get this: 当我尝试将变量分配给一个javascript时,这变得最糟:我得到了:

 "books":[{"image":"\/ara\/web\/uploads\/images\/slide\/32.jpeg"

and this is the code: 这是代码:

php: 的PHP:

$presentation_slide = json_encode($presentation_slides)

javascript: javascript:

<script>
    var presentation = {{ presentation_slides }}
</script>

I am using sumfony2 我正在使用sumfony2

Maybe you should use the JSON_UNESCAPED_SLASHES option: 也许您应该使用JSON_UNESCAPED_SLASHES选项:

http://php.net/manual/en/function.json-encode.php http://php.net/manual/zh/function.json-encode.php

$presentation = json_encode($presentation_slides, JSON_UNESCAPED_SLASHES);

The json_encoding function has numerous flags that you can pass to it, which enable the function to parse particular character sets. json_encoding函数具有许多可以传递给它的标志,这些标志使函数可以解析特定的字符集。 The following call ought to solve the problems you are having 以下电话应该可以解决您遇到的问题

json_encode($presentation_slides, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP );

$presentation = json_encode($presentation_slides, JSON_UNESCAPED_SLASHES);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM