【发布时间】:2012-03-27 18:11:05
【问题描述】:
假设我有一个返回 json 响应的 PHP 脚本。它看起来像这样:
$ctype = ContentNego::desiredContentType();
header("Content-Type: $ctype");
if (ContentNego::flavor($ctype) == ContentFlavor::JSON) {
echo '{ "name": "' . $name . '", ' .
'"comment": "' . $comment . '"}';
}
.... other content types here....
在上面的代码之前,我有
class ContentFlavor {
const XML = 1;
const JSON = 2;
const TEXT = 3;
const Unknown = 4;
}
$cftype 的值是通过检查传入的 Accept 标头来设置的,这是内容类型协商的基本形式。
php 脚本回显的字符串如下所示:
[ "name" : "Vettel", "comment" : "He's terrific" ]
在浏览器中,我有这样的javascript:
$.ajax({type: "GET",
url: url,
dataType: "json",
headers : { "Accept" : 'application/json' },
cache: false,
error: function (xhr, textStatus, errorThrown) {
enableEditboxButtons();
},
success: function (data, textStatus, xhr) {
// fill and show the editbox dialog
...
}});
但是当我在 jQuery 端收到这个内容时,我得到了这个:
[ "name" : "Vettel", "comment" : "He\'s terrific" ]
注意注入的反斜杠“转义”了撇号或单引号。我的代码没有把那个反斜杠放在那里。好像是PHP注入的?它似乎也违反了http://json.org规定的JSON编码要求:
带有转义撇号的 json 字符串无法在 jQuery 1.7.1 中解析,并且我的错误 fn 被调用。
有什么关系? PHP 真的在做这种转义吗,如果是,为什么/如何? (它在 Linux 上的 PHP 5.2.17 上运行)我可以避免它吗?
如果没有,我该如何解决这个问题?
【问题讨论】: