PHP Json 编码在 5.2 中带有引号转义?
我正在使用 flickr api 和 php。我想通过 Ajax 将一些信息从 PHP 传递到 Javascript。我有以下代码:
json_encode($pics);
产生以下示例 JSON 字符串:
[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]
然而,由于第二项中的未转义单引号(“不能否认”),Javascript 存在问题。
我想使用 json_encode 函数和 options 参数来去掉引号,但这仅在 PHP 5.3 中可用,而我正在运行 5.2(不是我的服务器)。有没有一种快速的方法来运行整个数组并在将其编码为 Json 之前转义所有内容?我寻找一种方法来做到这一点,但这一切似乎都是在生成数据时对其进行编码,这是我无法做到的,因为我不是生成数据的人。
如果有帮助的话,我目前在 ajax 请求后使用以下 javascript:
var photos = eval('(' + resptxt + ')');
I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code:
json_encode($pics);
which results in the following example JSON string:
[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]
Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny").
I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data.
If it helps, I'm currently using the following javascript after the ajax request:
var photos = eval('(' + resptxt + ')');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否考虑过使用 JSON2 而不是
eval( )
?详细信息此处。Have you considered using JSON2 instead of
eval()
? Details here.str_replace('\'', '\\'', json_encode($pics))
str_replace('\'', '\\'', json_encode($pics))
您必须执行(递归)foreach 来遍历数组并手动操作它们。您可以执行 str_replace,但 addslashes 也可以正常工作(并且 addcslashes 甚至更好。)
You'll have to do a (recursive) foreach to walk through the array and manipulate them manually. You can do a str_replace, but addslashes works just as fine (and addcslashes is even better.)