繁体   English   中英

如何用jQuery 1.8.3的实现替换jQuery 1.9.1的$ .parseJSON函数

[英]How To Replace jQuery 1.9.1's $.parseJSON function with the implementation from jQuery 1.8.3

jQuery从1.9.0版开始更改了$ .parseJSON的实现,我们确实依赖早期版本的jQuery解析null和空字符串的方式,例如jQuery过去不会抛出异常,并且会为null和empty返回null值串。

在编写本文时,我们想使用jQuery的最新版本,该版本是1.9.1,但是要替换$ .parseJSON的实现。

说明从jQuery进行更改的文档: http : //api.jquery.com/jQuery.parseJSON/

我们是否可以使用一些JavaScript来告诉jQuery,将$ .parseJSON函数的“自然”版本替换为具有相同名称的另一个实现/函数... jQuery 1.8.3的版本?

http://code.jquery.com/jquery-1.8.3.js具有我们所需的函数实现。

如果需要,请按照以下方式进行操作:

jQuery._parseJSON = jQuery.parseJSON;

jQuery.parseJSON = function( data ) {

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

    return jQuery._parseJSON( data );

}

我不推荐,但是如果您仍然想做的话

创建一个jquery-override.js文件,并将以下内容添加到其中

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

        // Make sure leading/trailing whitespace is removed (IE can't handle it)
        data = jQuery.trim( data );

        // Attempt to parse using the native JSON parser first
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }

        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        if ( rvalidchars.test( data.replace( rvalidescape, "@" )
            .replace( rvalidtokens, "]" )
            .replace( rvalidbraces, "")) ) {

            return ( new Function( "return " + data ) )();

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

然后在jquery-1.9.1.js文件之后包含此文件

如果您的问题与在jQuery的$ .ajax()方法的上下文中发生的$ .parseJSON()调用有关,那么这里是一个不错的解决方案。 您可以通过设置如下转换器来覆盖从JSON字符串到JS对象的默认转换:

$.ajaxSetup({ 
            converters: { "text json": function (jsonString) {
                var jsonObj = mySpecialParsingMethod(jsonString);
                return jsonObj;
            } }
});

如果您不问有关$ .ajax()方法的问题,那么就不要介意了。 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM