日期:2014-05-16  浏览次数:20328 次

dojo.toJson不支持正则序列化的解决方法
dojo把一个对象序列化成json时,如果对象中包含正则表达式,正则表达式会被转换为{},而不能转换为toString()形式,可以给dojo打个补丁,参看如下加粗代码:

/**
* dojo.toJson方法,增加正则表达式支持
*/
dojo.toJson = function(/*Object*/it, /*Boolean?*/ prettyPrint, /*String?*/ _indentStr){
    if (it === undefined) {
        return "undefined";
    }
    var objtype = typeof it;
    if (objtype == "number" || objtype == "boolean") {
        return it + "";
    }
    if (it === null) {
        return "null";
    }
    if (it instanceof RegExp) {
        return it.toString();
    }
   
    if (dojo.isString(it)) {
        return dojo._escapeString(it);
    }
    var recurse = arguments.callee;
    var newObj;
    _indentStr = _indentStr || "";
    var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
    var tf = it.__json__ || it.json;
    if (dojo.isFunction(tf)) {
        newObj = tf.call(it);
        if (it !== newObj) {
            return recurse(newObj, prettyPrint, nextIndent);
        }
    }
    if (it.nodeType && it.cloneNode) {
        throw new Error("Can't serialize DOM nodes");
    }
    var sep = prettyPrint ? " " : "";
    var newLine = prettyPrint ? "\n" : "";
    if (dojo.isArray(it)) {
        var res = dojo.map(it, function(obj){
            var val = recurse(obj, prettyPrint, nextIndent);
            if (typeof val != "string") {
                val = "undefined";
            }
            return newLine + nextIndent + val;
        });
        return "[" + res.join("," + sep) + newLine + _indentStr + "]";
    }
    if (objtype == "function") {
        return null;
    }
    var output = [], key;
    for (key in it) {
        var keyStr, val;
        if (typeof key == "number") {
            keyStr = '"' + key + '"';
        }
        else
            if (typeof key == "string") {
                keyStr = dojo._escapeString(key);
            }
            else {
                continu