簡體   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