jQuery.parseJSON -> jQuery 1.4版的json处理

来源:互联网 发布:免费 php cms 编辑:程序博客网 时间:2024/05/16 18:27


最近在做查询报表,前端显示部分使用了flexigrid (详细)。 之前也考虑了ext,但从团队角度考虑“成本”过高,而且我个人也偏好jQ多一些 :) 。

因为 flexigrid 在展现形式上和 Ext.grid 比较接近,所以选择了它。

flexigrid 的数据源要求是 json or xml ,为了图便捷我使用了 json 做它的数据源,首先写了一个简单的demo 测试了一下,很快的就调通了,

心想可以在项目中使用了。于是开始了相关业务的编写,许久之后相关部分完成了,兴致勃勃准备用 flexigrid 来查看一下成果, flexigrid 它却罢工了。

诧异的同时我开始了调试,在确保业务及逻辑无误的情况下我查看了 json 输出,将输出放在之前的 demo 中测试则是正常运行,

于是我开始寻找差异, demo 中的jQ 版本是1.2.6 而我一直习惯使用jQ最新版 所以项目中是 1.4.2

在更换了版本之后问题消失了,看来问题可能不单是 flexigrid 的问题 也可能是 flexigrid 与 jQ 关联的部分。

于是编辑了flexigrid.js 用于调试,发现错误的信息是 parse error 问题是出在 json 的转换上,那两个版本之间有什么不同呢?

1.2.6

// Get the JavaScript object, if JSON is used.
if ( type == "json" )
 data = eval("(" + data + ")");

1.4.2

// Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
 data = jQuery.parseJSON( data );

http://code.jquery.com/jquery-1.4.2.js


parseJSON: function( data ) {
  if ( typeof data !== "string" || !data ) {
   return null;
  }

  // Make sure leading/trailing whitespace is removed (IE can't handle it)
  data = jQuery.trim( data );
  
  // Make sure the incoming data is actual JSON
  // Logic borrowed from http://json.org/json2.js
  if ( /^[/],:{}/s]*$/.test(data.replace(///(?:["////bfnrt]|u[0-9a-fA-F]{4})/g, "@")
   .replace(/"[^"///n/r]*"|true|false|null|-?/d+(?:/./d*)?(?:[eE][+/-]?/d+)?/g, "]")
   .replace(/(?:^|:|,)(?:/s*/[)+/g, "")) ) {

   // Try to use the native JSON parser first
   return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

  } else {
   jQuery.error( "Invalid JSON: " + data );
  }
 }

原来是 jQuery.parseJSON 的缘故

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

 

jQuery.parseJSON


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

dataType                                  String

Default: Intelligent Guess (xml, json, script, or html)


"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.)