JSON数据的序列化方法

 ajax传参是json数据对象时,最好是将json对象先序列化

var stuAnswerTotal = examModule.touch.getData('examAnswer');

  console.log(stuAnswerTotal);//Object对象如下

       "id" : 1702,
       "type":"1",
                 "val":["",'""]
       "id" : 1703,
       "type":"1",
                 "val":[""]
       "id" : 1704,
       "type":"1",
                 "val":["B"]

        var answer = {};
        $.each(stuAnswerTotal,function(k,v){
            answer[k] = v.val
   });
       var stuAnswer = xue.JSON.stringify(answer);//调用序列化方法

  console.log(stuAnswer)// 序列化{"17072":[],"17073":[],"17074":["B"]}

/**
 * 增加对JSON数据的序列化方法,
 * 主要用于IE6、7不支持JSON对象的浏览器
 */
xue.json = xue.json || {};

xue.json.stringify = function(obj) {
    //如果是IE8+ 浏览器(ff,chrome,safari都支持JSON对象),使用JSON.stringify()来序列化
    if (window.JSON) {
        return JSON.stringify(obj);
    }
    var t = typeof(obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);
    } else {
        // recurse array or object
        var n, v, json = [],
            arr = (obj && obj.constructor == Array);

        // fix.
        var self = arguments.callee;

        for (n in obj) {
            v = obj[n];
            t = typeof(v);
            if (obj.hasOwnProperty(n)) {
                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null)
                // v = jQuery.stringify(v);
                    v = self(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};