最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.parse ends up in 'missing ) after argument list' - Stack Overflow

programmeradmin0浏览0评论

I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().

Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).

clippings:

<script>
(function($) {
    var prices = JSON.parse('<?= $this->prices_json; ?>'); ...

... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...

  1. have single quotes to be escaped? If so, how best to do it?
  2. is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?

I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().

Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).

clippings:

<script>
(function($) {
    var prices = JSON.parse('<?= $this->prices_json; ?>'); ...

... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...

  1. have single quotes to be escaped? If so, how best to do it?
  2. is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
Share Improve this question asked Feb 21, 2018 at 9:08 simisimi 291 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

have single quotes to be escaped?

Single quotes inside a JavaScript string literal that is delimited with single quotes do have to be escaped.

… and that is what you have: 'data with ' and then at the end'.

If so, how best to do it?

To not use a JavaScript string literal at all.

JSON is a subset of JavaScript literal notation, so just treat it as JavaScript. Don't try wrapping it in a string and then explicitly parsing it.

var prices = <?= $this->prices_json; ?>;

try php: addslashes(json_encode($php array))

have single quotes to be escaped? If so, how best to do it?

json_encode should escape everything needs to be escaped.

is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?

You should use json_encode in order to be sure that the output is correct. Do not rely on default array output. It has nothing to do with JSON.

You don't need to use JSON.parse here at all.

var prices = <?= json_encode($this->prices_json); ?>;

发布评论

评论列表(0)

  1. 暂无评论