为什么 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());
给了我下面的结果:
Doing a alert(data.toSource());
gives me the dollowing result:
({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屋!