我遇到没有正确获取HTML编码值,其中jQuery读取属性值 - 引号被解码 - 因此JSON解析失败并带有此值。
这是jQuery中的错误还是我没有正确编码我的值?
这是我的HTML编码的JSON字符串:
[
{
"id": "1",
"organisation_id": "1",
"badge_id": "49",
"target": "15",
"target_type": "actions",
"target_title": null,
"target_description": null,
"start": "2014-01-15",
"name": "Our goal",
"description": "Vestibulum id ligula porta felis euismod semper. "Nullam" id dolor id nibh ultricies vehicula ut id elit. Nulla vitae elit libero, a pharetra augue. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.",
"created": "2013-08-07 14:26:56"
},
{
"id": "19",
"organisation_id": "1",
"badge_id": "49",
"target": "30000000",
"target_type": "numeric",
"target_title": "Revenue contribution",
"target_description": "Specify how much this action contributes to the revenue goal",
"start": "2014-01-21",
"name": "November revenue",
"description": "Reach revenue of $30,000,000 in November. Let's do this.",
"created": "2014-01-21 16:59:25"
}
]
请注意"
属性中的description
。
以下是该问题的复制品:http://jsfiddle.net/J8Xv6/
我认为这是一个出现在较新版本的jQuery中的问题。刚刚从1.7.x更新到1.11.0。
答案 0 :(得分:2)
这是无效的JSON。当字符串进入JavaScript时,该HTML实体将成为双引号字符。必须使用反斜杠转义字符串中的双引号字符。
字符的HTML编码使HTML解析器满意,但它会产生一个属性值,该值在JSON值(字符串常量)的中间有一个简单的双引号字符。
如果你在HTML实体之前放一个反斜杠,它将是有效的JSON。
编辑 - 在你的jsfiddle中,你试图用jQuery .data()
方法获取data属性。这很好,但请注意,当jQuery看到看起来像 JSON的东西时,它会尝试为你解析它。因此,当您返回属性值时,它已经被解析。
答案 1 :(得分:0)
您的属性以这种方式获取数据,
"[{"id":"1","organisation_id":"1","badge_id":"49","target":"15","target_type":"actions","target_title":null,"target_description":null,"start":"2014-01-15","name":"Our goal","description":"Vestibulum id ligula porta felis euismod semper. "Nullam" id dolor id nibh ultricies vehicula ut id elit. Nulla vitae elit libero, a pharetra augue. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.","created":"2013-08-07 14:26:56"},{"id":"19","organisation_id":"1","badge_id":"49","target":"30000000","target_type":"numeric","target_title":"Revenue contribution","target_description":"Specify how much this action contributes to the revenue goal","start":"2014-01-21","name":"November revenue","description":"Reach revenue of $30,000,000 in November. Let's do this.","created":"2014-01-21 16:59:25"}]"
错误将引发粗体字,双引号包含内部双引号。
"
Vestibulum id ligula porta felis euismod semper。 “Nullam” id dolor id nibh ultricies vehicula ut id elit。 Nulla vitae elit libero,一个pharetra augue。 Lorem ipsum dolor坐下来,精致的adipistur elit。 Praesent commodo cursus magna,vel scelerisque nisl consectetur et。"