zoukankan      html  css  js  c++  java
  • jquery工具方法parseJSON

    error : 自定义错误

    parseJSON : 字符串转json

    trim : 去除字符串头尾空字符

    parseJSON方法先判断参数是否为字符串,否则返回空对象,再去除字符串头尾空字符,判断是否支持window.JSON.parse,否则使用json2.js中的方法。

    var core_trim = String.prototype.trim,
        // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
        rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g,
        // JSON RegExp
        rvalidchars = /^[],:{}s]*$/,
        rvalidbraces = /(?:^|:|,)(?:s*[)+/g,
        rvalidescape = /\(?:["\/bfnrt]|u[da-fA-F]{4})/g,
        rvalidtokens = /"[^"\
    ]*"|true|false|null|-?(?:dd*.|)d+(?:[eE][-+]?d+|)/g;
    
    
    jQuery.extend({
    
        ......................
    
        error: function( msg ) {
            throw new Error( msg );
        },
    
        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 );
        },
    
        // Use native String.trim function wherever possible
        trim: core_trim && !core_trim.call("uFEFFxA0") ?
            function( text ) {
                return text == null ?
                    "" :
                    core_trim.call( text );
            } :
    
            // Otherwise use our own trimming functionality
            function( text ) {
                return text == null ?
                    "" :
                    ( text + "" ).replace( rtrim, "" );
            },
    
        ...............
    
    });
  • 相关阅读:
    可视化数据库管理工具DataGrip使用详解
    MySQL常用函数
    你必须掌握的 21 个 JAVA 核心技术!
    idea中那些好用到飞起的插件
    Object使用
    单页面应用和多页面应用的区别及优缺点
    正则常用匹配
    npm --save-dev 和 --save 的区别
    js常用小技巧
    js复制文字到剪切板
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/5902078.html
Copyright © 2011-2022 走看看