单位的项目,使用了json来传递数据,IE7+是没问题的,不知道哪个用户竟然还使用IE6,悲催的报错了,现在要修改,请教各位大大方法。使用的是jquery 和 jquery.json.js
var str=JSON.stringify($(".txtAddOddts").val()); //将JSON对象转化为JSON字符串
现在需要把Json对象转换为字符串来供后台代码使用,但这句在IE6下使用不了百度了好多,都只是用json.js来转换的,不知道iE6中怎么解决。请教各位大大帮忙,开发工具vs2005

解决方案 »

  1.   

    手动转换怎么转?
    我查到的方法都是用json.js来帮忙转
      

  2.   

    我上边贴错了,
    我之前用的IE7+有用的语句是
    var str=$.toJSONString($(".txtAddOddts").val());     // 将JSON对象转化为JSON字符顶楼的是我后来试的方法,没用
      

  3.   

    我用java转怎么没出现过IE6不兼容的问题呢?IE都可以啊!
      

  4.   

    IE7是个IE的一个过渡版本 里面问题挺多的 目前IE6仍有大批用户在用
    楼主的那个json前台转换有问题 我们可以采取后台转换 不必非得在前台转
      

  5.   

    那请教一下5楼 后台怎么转换才能获得 string类型的json字符串?
      

  6.   

    4楼我不知道什么情况啊,我编码的时候只测了IE7和8都没问题,
    但现在用户说IE6有问题,我测了下果然是
    我之前用json.js 转换的方法也是从网上搜的
    难道是这个js文件不支持ie6?
      

  7.   

    LZ的目的是在前台把json转为string给后台处理是吧 但是
    var str=$.toJSONString($(".txtAddOddts").val()); // 将JSON对象转化为JSON字符
    这句话能把json对象转为string? 
    (".txtAddOddts").val()取出来的值就是个string类型的啊?所以 我想先问LZ是前台要把string转json还是json转string?
      

  8.   

    给你一个老道写的转换工具
    https://raw.github.com/douglascrockford/JSON-js/master/json2.js用法:
    <script src="./json2.js"></script>
    <script>
    var test = {
    testObj: [
    {a:'b', c:'d'},
    {a:{b:'c'}, d:'e'},
    {a:['b', 'c'], d:'e'}
    ]
    };
    console.log(JSON.stringify(test));
    // output {"testObj":[{"a":"b","c":"d"},{"a":{"b":"c"},"d":"e"},{"a":["b","c"],"d":"e"}]}
    </script>
      

  9.   

    试试这个类库,我这里IE6测试没得问题最新Json.js文件下载
    array.toJSONString()
            boolean.toJSONString()
            date.toJSONString()
            number.toJSONString()
            object.toJSONString()
            string.toJSONString()
      

  10.   

    我也遇到过这个问题,JSON.stringify 在ie6下不支持的,解决方案是用到了 json.js
      

  11.   

    我需要把json对象转换为string类型的 json字符串
    就是吧 {XX:yy}  转换成 “{xx:yy}”
    前者是json对象 alert弹出结果是[object]  后者alert弹出结果为“{xx:yy}”8楼
    $(".txtAddOddts").val() 是一个Json对象
    用alert得到的结果是 object9楼 11楼 我现在在公司,没办法上网,只能查百度快照和上csdn,所以下载不了。。
    有没人贴段转换的代码或者什么。。12楼 我目前用的就是json.js 不过是jquery.json.js, JSON.stringify是我后来找的方法没用
      

  12.   

    json.js和jquery.json.js不一样的,json.js并不是居于jquery写的。/*
        json.js
        2007-08-05    Public Domain    This file adds these methods to JavaScript:        array.toJSONString()
            boolean.toJSONString()
            date.toJSONString()
            number.toJSONString()
            object.toJSONString()
            string.toJSONString()
                These methods produce a JSON text from a JavaScript value.
                It must not contain any cyclical references. Illegal values
                will be excluded.            The default conversion for dates is to an ISO string. You can
                add a toJSONString method to any date object to get a different
                representation.        string.parseJSON(filter)
                This method parses a JSON text to produce an object or
                array. It can throw a SyntaxError exception.            The optional filter parameter is a function which can filter and
                transform the results. It receives each of the keys and values, and
                its return value is used instead of the original value. If it
                returns what it received, then structure is not modified. If it
                returns undefined then the member is deleted.            Example:            // Parse the text. If a key contains the string 'date' then
                // convert the value to a date.            myData = text.parseJSON(function (key, value) {
                    return key.indexOf('date') >= 0 ? new Date(value) : value;
                });    It is expected that these methods will formally become part of the
        JavaScript Programming Language in the Fourth Edition of the
        ECMAScript standard in 2008.    This file will break programs with improper for..in loops. See
        http://yuiblog.com/blog/2006/09/26/for-in-intrigue/    This is a reference implementation. You are free to copy, modify, or
        redistribute.    Use your own copy. It is extremely unwise to load untrusted third party
        code into your pages.
    *//*jslint evil: true */// Augment the basic prototypes if they have not already been augmented.if (!Object.prototype.toJSONString) {    Array.prototype.toJSONString = function () {
            var a = [],     // The array holding the partial texts.
                i,          // Loop counter.
                l = this.length,
                v;          // The value to be stringified.
    // For each value in this array...        for (i = 0; i < l; i += 1) {
                v = this[i];
                switch (typeof v) {
                case 'object':// Serialize a JavaScript object value. Ignore objects thats lack the
    // toJSONString method. Due to a specification error in ECMAScript,
    // typeof null is 'object', so watch out for that case.                if (v) {
                        if (typeof v.toJSONString === 'function') {
                            a.push(v.toJSONString());
                        }
                    } else {
                        a.push('null');
                    }
                    break;            case 'string':
                case 'number':
                case 'boolean':
                    a.push(v.toJSONString());// Values without a JSON representation are ignored.            }
            }// Join all of the member texts together and wrap them in brackets.        return '[' + a.join(',') + ']';
        };
        Boolean.prototype.toJSONString = function () {
            return String(this);
        };
        Date.prototype.toJSONString = function () {// Eventually, this method will be based on the date.toISOString method.        function f(n) {// Format integers to have at least two digits.            return n < 10 ? '0' + n : n;
            }        return '"' + this.getUTCFullYear() + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate()) + 'T' +
                    f(this.getUTCHours()) + ':' +
                    f(this.getUTCMinutes()) + ':' +
                    f(this.getUTCSeconds()) + 'Z"';
        };
        Number.prototype.toJSONString = function () {// JSON numbers must be finite. Encode non-finite numbers as null.        return isFinite(this) ? String(this) : 'null';
        };
        Object.prototype.toJSONString = function () {
            var a = [],     // The array holding the partial texts.
                k,          // The current key.
                v;          // The current value.// Iterate through all of the keys in the object, ignoring the proto chain
    // and keys that are not strings.        for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':// Serialize a JavaScript object value. Ignore objects that lack the
    // toJSONString method. Due to a specification error in ECMAScript,
    // typeof null is 'object', so watch out for that case.                    if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' + v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;                case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());// Values without a JSON representation are ignored.                }
                }
            }// Join all of the member texts together and wrap them in braces.        return '{' + a.join(',') + '}';
        };
        (function (s) {// Augment String.prototype. We do this in an immediate anonymous function to
    // avoid defining global variables.// m is a table of character substitutions.        var m = {
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };
            s.parseJSON = function (filter) {
                var j;            function walk(k, v) {
                    var i;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                v[i] = walk(i, v[i]);
                            }
                        }
                    }
                    return filter(k, v);
                }
    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.// We split the first stage into 3 regexp operations in order to work around
    // crippling deficiencies in Safari's regexp engine. First we replace all
    // backslash pairs with '@' (a non-JSON character). Second we delete all of
    // the string literals. Third, we look to see if only JSON characters
    // remain. If so, then the text is safe for eval.            if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(this.
                        replace(/\\./g, '@').
                        replace(/"[^"\\\n\r]*"/g, ''))) {// In the second stage we use the eval function to compile the text into a
    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
    // in JavaScript: it can begin a block or an object literal. We wrap the text
    // in parens to eliminate the ambiguity.                j = eval('(' + this + ')');// In the optional third stage, we recursively walk the new structure, passing
    // each name/value pair to a filter function for possible transformation.                return typeof filter === 'function' ? walk('', j) : j;
                }// If the text is not JSON parseable, then a SyntaxError is thrown.            throw new SyntaxError('parseJSON');
            };
            s.toJSONString = function () {// If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can simply slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe
    // sequences.            if (/["\\\x00-\x1f]/.test(this)) {
                    return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    }) + '"';
                }
                return '"' + this + '"';
            };
        })(String.prototype);
    }
      

  13.   

    14楼
    我知道json.js 和jquery.json.js 不一样
    但是我的项目里面用到了 jquery.js 后json.js 是无效的,
    只能用jquery.json.js
      

  14.   

    jquery没有toJSONString方法吧?不会冲突啊,jquery1.6增加了这个方法?
      

  15.   

    jquery里是没有toJSONString方法
    所以我引入了 jquery.json.js
    但是IE7+是有效的
    偏偏IE6无效
      

  16.   

    你自己不是都说了,jq的那个plugin在IE6出错json.js这个文件在哪个浏览器都能用,直接用json.js这个就行了,你只需要修改原来的JSON.stringify($(".txtAddOddts").val())修改为xxx.toJSONString()。不过不知道jquery.json.js怎么写的,是否也将jquery包装的对象进行一些特殊解压,去掉一些不必要的属性什么的,如果是这样,json.js不满足你的要求
    json.js就是将原始的json对象转换成字符串
      

  17.   

    我的项目中已经用了jquery.js
    如果再用json.js  就冲突了,json.js就是将原始的json对象转换成字符串这个就没有效果
      

  18.   

    jquery.js只能和 jquery.json.js一起用
      

  19.   


    你试过了??我这里用的jq1.4.4和json.js没有冲突。
    json.js只是给array,        boolean,        date,        number,        object,        string增加了一个原型方法toJSONString除非你的jquery.json.js或者jqeury添加了这个原型方法,否则100%不会冲突
      

  20.   

    我确定我冲突了
    你百度下 “json.js和jquery冲突”就知道 冲突的不只我一个人。
    而且我公司项目里的jquery版本貌似很低 估计是1.3或者以下的版本。。要不我弄个高点版本的jquery来试试看。。
      

  21.   

    试试用 https://github.com/douglascrockford/JSON-js/blob/master/json2.js
    json2.js和jquery一起用。