为什么json_encode添加反斜杠? [英] Why is json_encode adding backslashes?
问题描述
我已经使用json_encode
很长时间了,到目前为止我还没有遇到任何问题.
现在,我正在使用上传脚本,并且尝试在文件上传后返回一些JSON数据.
I've been using json_encode
for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
我有以下代码:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
这给了我以下结果:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
有人可以告诉我为什么json_encode
添加斜线吗?
Can anyone tell me why json_encode
adds slashes?
更新
@Quentin说json_encode
和.parseJSON
之间发生了某些事情,他是对的.
@Quentin said that something is happening between json_encode
and .parseJSON
and he's right.
执行alert(data.toSource());
给我以下结果:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
这不是有效的JSON.它还添加了status:200
,我不知道它来自哪里.
And this is not valid JSON. It also adds the status:200
and I have no idea where this comes from.
Plupload bind
是否会对我返回的数据有所帮助?
Could it be that the Plupload bind
does something to my returned data?
这是我的js脚本:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});
推荐答案
有人可以告诉我为什么json_encode添加斜线吗?
Can anyone tell me why json_encode adds slashes?
正斜杠字符嵌入到HTML脚本元素中时,可能会导致问题(在<
之前触发脚本元素结尾"的SGML规则).为防患于未然.
Forward slash characters can cause issues (when preceded by a <
it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
因为当我尝试使用jQuery.parseJSON(response);在我的js脚本中,它返回null.所以我想这与斜杠有关.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
不是.在JSON中,"/"
和"\/"
是等效的.
It doesn't. In JSON "/"
and "\/"
are equivalent.
您在问题中列出的JSON有效(您可以使用 jsonlint 进行测试).您的问题可能与json_encode
和parseJSON
之间发生的事情有关.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode
and parseJSON
.
这篇关于为什么json_encode添加反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!