日期:2014-05-16  浏览次数:20288 次

关于jQuery1.4.2的json格式问题

最近由于项目需要学习了jquery时遇到了关于json格式问题,今天写出来希望能帮助初学者少走弯路。

$.ajax({
????url : '<%=basePath%>task.do?method=loadTaskList',
????dataType : 'json',????
????success : function(obj){?????
????? json=obj.data;?
?????$("#show").attr("border",1);
?????$.each(json,function(i){
??????$("#show").append("<tr><td><input type='checkbox' value="+json[i].taskId+"/></><td>"+json[i].taskTitle+"</td><td>"+json[i].taskData+"<td></tr>");
?????});?????
????},
????error : function(){
?????alert('失败!');
????}
????
???});?

服务器返回的数据格式为:{data:[{id:"1",name:"sss"},{id:"2",name:'ccc'}]}

这段代码在jQuery为1.4 的版本时会一直调用error函数,而把jQuery库换为1.3.1后执行成功!

在网上找了些资料才发现原来1.4.2这个版本中jqurey把JSON的解析由原来的eval改为极其严格的$.parseJSON()来处理了。

http://api.jquery.com/jQuery.ajax/?官方的说明文档中有说明,如下:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

意思是说 jQuery 1.4对服务端返回的JSON 数据要求比较严格,必须严格按照JSON的标准来了。

那什么样的格式才是JSON的标准格式呢?

http://api.jquery.com/jQuery.parseJSON/

从文档上来看

  • {test: 1} (test does not have double quotes around it).? //test两边必须有双引号{"test":1}
  • {'test': 1} ('test' is using single quotes instead of double quotes). //test两边的引号不能为单引号,必须为是双引号
  • 由此可见JSON的标准格式:

    {"test":1}

    {"test":"aa"}

    {"test":["black":"cc","id":1]}