php json_encode& jQuery parseJSON单引号问题 [英] php json_encode & jquery parseJSON single quote issue
问题描述
我搜索并阅读了大多数相关主题,但这些并不是我想要的.
I searched and read most of the related topics, but they weren't what I was looking for.
我有一个json_encode
PHP函数的JSON编码字符串:
I've a JSON enocded string with json_encode
PHP function:
{"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987}
在测试的情况下,我也使用jQuery将值也放入适当的字段中:
I'm working with jQuery to put the values in appropriate fields too, in the case of testing I did the below:
<script>
var obj = jQuery.parseJSON('<?=$data?>');
console.log(obj);
</script>
假设$ data是这样的:
Suppose that $data is this:
$data =
<<<END
{"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987}
END;
在这种情况下,Google chrome控制台会产生什么:
What Google chrome console produces in this case:
Uncaught SyntaxError: Unexpected identifier
但是,当我更改JSON编码的字符串时-在单引号中添加反斜杠:
However when I make a change in JSON encoded string - adding Backslash to single quote :
{"casts":["Matthew Modine","Adam Baldwin","Vincent D\'Onofrio"],"year":1987}
控制台输出正常:
Object {casts: Array[3], year: 1987}
casts: Array[3]
year: 1987
问题:控制台中是否会出现此错误?我认为转义'
或将'
替换为\'
会很脏!
The question: is this error in console expected? I think escaping or replacing '
with \'
will be so dirty!
已更新
UPDATED
实际上 $ data 值来自json_encode($var)
,而$ var是一个数组!
Actually $data value comes from a json_encode($var)
and $var is an array!
$data = json_encode($var);
推荐答案
但是,当我更改JSON编码的字符串时-将反斜杠添加到单引号
However when I make a change in JSON encoded string - adding Backslash to single quote
在PHP字符串文字中将其转义.然后将其作为简单的'
插入到PHP字符串中.
That escapes it in the PHP string literal. It is then inserted into the PHP string as a simple '
.
如果要在将其插入JavaScript之前对其进行转义,则需要在字符串中添加斜杠,以得到
If you want to escape it before inserting it into JavaScript then you need to add slashes to the string you get out of json_encode
(or rather, since you aren't using that (you should be!) the JSON string you build by hand).
那是您需要做的更多工作.真正的解决方案是记住JSON是JavaScript文字语法的子集:
That is more work then you need though. The real solution is to remember that JSON is a subset of JavaScript literal syntax:
var obj = <?=$data?>;
这篇关于php json_encode& jQuery parseJSON单引号问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!