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


最近在做查詢報表,前端顯示部分使用了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.)

發佈了63 篇原創文章 · 獲贊 7 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章