【发布时间】:2011-11-19 17:10:17
【问题描述】:
我正在从 PHP 数组创建一个 JSON 字符串。我使用json_encode()对其进行了编码。
$data = array(
'title' => 'Example string\'s with "special" characters'
);
$data = json_encode( $data );
$data 使用 wp_localize_script() 进行本地化,并可通过全局 data 变量访问。
在 JS 文件中,我可以通过以下方式访问信息:
var data = data.replace( /"/g, '"' ),
jsonData = jQuery.parseJSON( data );
console.log( jsonData );
这导致输出:
{ "title":"Example string's with "special" characters" }
将该结果输入http://jsonlint.com/ 会返回错误。删除 "special" 周围的双引号可以验证字符串。
从 PHP 创建 JSON 字符串并正确转义以在 JS 文件中使用的最佳方法是什么?
【问题讨论】:
-
任何阅读此 Q 及其答案的人:请注意,在问题中,json 字符串
data在传递给 parseJSON 之前在 JS 中已更改。通过调用wp_localize_script和replace。恕我直言,这并没有说明 json_encode 或 parseJSON 存在问题。
标签: php escaping json double-quotes