转:jQuery1.4.2与json格式兼容问题

原来使用jQuery1.3.2编写的代码,更换到1.4.2后,使用jQuery.ajax()加载的json文件,不能正常加载。(使用jQuery.getJSON()也一样)

 

原json文件内容为:

{
    label: 'Europe (EU27)',
    data: [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
}

 

解决方法一:

改成标准的json格式,要求对字符串都使用""限定,修改后的内容为:

{
    "label": "Europe (EU27)",
    "data": [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
}

 

这样就可以正常加载了。

 

解决方法二:

在jQuery-1.4.2.js中找到"parseJSON: function",可发现有如下代码:

Js代码 
       // 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 );   }  

// Logic borrowed from http://json.org/json2.jsif
( /^[\],:{}\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 firstreturn
window.JSON && window.JSON.parse ?window.JSON.parse( data ) :(new Function("return " + data))();
}
else {
jQuery.error( "Invalid JSON: " + data );
}

在httpData: function中用到了parseJSON函数:

Js代码

// Get the JavaScript object, if JSON is used.   

        if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {   

         data = jQuery.parseJSON( data );  

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

 

在jQuery1.3.2中,没有parseJSON这个方法,而是直接使用下面的代码。

Js代码

// Get the JavaScript object, if JSON is used.   

       if ( type == "json" )   

      data = window["eval"]("(" + data + ")");  

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

替换成原来1.3.2的代码就可以了。

posted @ 2010-07-23 17:11  边走边睡  阅读(1237)  评论(0编辑  收藏  举报