【问题标题】:How to avoid parseerror when the JSON response delivered by PHP includes a single-quote or apostrophe?当 PHP 传递的 JSON 响应包含单引号或撇号时,如何避免 parseerror?
【发布时间】: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 上运行)我可以避免它吗?

如果没有,我该如何解决这个问题?

【问题讨论】:

    标签: php ajax json jquery


    【解决方案1】:

    Cheeso,确保在 PHP 配置中关闭 *magic_quotes_gpc* 和 *magic_quotes_runtime* 选项(可能会在此处放置反斜杠,更多信息 here)。

    此外,如果可以的话,您可能应该使用json_encode 方法,因为您可以将数组或对象直接传递给它并获取所表示数据的 JSON 版本,从而使生活变得更加轻松。

    【讨论】:

      【解决方案2】:

      我搜索并找到了this

      我将此代码放在我的浏览器端脚本中,它在文档就绪时运行一次。

      $.ajaxSetup({
          // Apparently, when sending application/json, if there is a
          // single-quote contained in a string value, PHP erroneously escapes
          // it.  This causes jQuery to barf with a parsererror.
          //
          // To work around the problem, use a custom converter to fixup
          // that invalid json serialization.
          //
          // e.g. { "comment": "Grandma\'s sweater" } -->
          //          { "comment": "Grandma's sweater" }
          converters: {
              "text json": function (textValue) {
                  return jQuery.parseJSON(textValue.replace(/(^|[^\\])\\'/g, "$1'"));
              }
          }
      });
      

      我仍然不清楚撇号是如何或为什么会出现在其中的,但是当浏览器接收到 JSON 时,这会将其去掉。

      【讨论】:

      • 不要关注这个答案。内森的回答更好。
      猜你喜欢
      • 2018-11-15
      • 2010-12-27
      • 1970-01-01
      • 2021-09-12
      • 2017-01-07
      • 2017-02-18
      • 1970-01-01
      • 2012-03-23
      相关资源
      最近更新 更多