以前写了一个jQuery版的 N 级联动插件,在jQuery 1.3.2中运行正常。
最近jQuery update 到 1.4.2,发现不能取数据了。经过 google 和其官方文档,找到原因:
jQuery.getJSON(url, data, callback)
http://api.jquery.com/jQuery.getJSON/
The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the$.parseJSON()
method.
就是说 jQuery 1.4 是用parseJSON()来解析返回的json数据的,而parseJSON()对数据要求比较严格
http://api.jquery.com/jQuery.parseJSON/
Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:
{test: 1}
(test does not have double quotes around it).必须用两引号{'test': 1}
('test' is using single quotes instead of double quotes).不能用单引号
Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation ofJSON.parse
, jQuery uses it to parse the string. For details on the JSON format, seehttp://json.org/.
所以,返回的JSON数据必须严格按上面的要求定义,而1.3好象用的是eval来返回一个对象,所以就没有那么严格了。修改了一个返回的JSON格式,原来的插件不需要修改一行代码,可以正常运行了。