日期:2014-05-16 浏览次数:20442 次
/* phpserializer.js - JavaScript to PHP serialize / unserialize class. * * This class is designed to convert php variables to javascript * and javascript variables to php with a php serialize unserialize * compatible way. * * Copyright (C) 2006 Ma Bingyao <andot@ujn.edu.cn> * Version: 3.0c * LastModified: Jun 2, 2006 * This library is free. You can redistribute it and/or modify it. * http://www.coolcode.cn/?p=171 * *2011-01-05 likefei edit without encoding *ser_string() *unser_string() * *gbk encoding *不同的编码中文的长度不同,需要调整一下函数 *chkLength(strTemp) */ function serialize(o) { var p = 0, sb = [], ht = [], hv = 1; function classname(o) { if (typeof(o) == "undefined" || typeof(o.constructor) == "undefined") return ''; var c = o.constructor.toString(); c = utf16to8(c.substr(0, c.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '')); return ((c == '') ? 'Object' : c); } function is_int(n) { var s = n.toString(), l = s.length; if (l > 11) return false; for (var i = (s.charAt(0) == '-') ? 1 : 0; i < l; i++) { switch (s.charAt(i)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default : return false; } } return !(n < -2147483648 || n > 2147483647); } function in_ht(o) { for (k in ht) if (ht[k] === o) return k; return false; } function ser_null() { sb[p++] = 'N;'; } function ser_boolean(b) { sb[p++] = (b ? 'b:1;' : 'b:0;'); } function ser_integer(i) { sb[p++] = 'i:' + i + ';'; } function ser_double(d) { if (d == Number.POSITIVE_INFINITY) d = 'INF'; else if (d == Number.NEGATIVE_INFINITY) d = '-INF'; sb[p++] = 'd:' + d + ';'; } function ser_string(s) { //var utf8 = utf16to8(s); var utf8 = s;//当判断是中文时不进行编码转换 sb[p++] = 's:' + chkLength(utf8) + ':"'; sb[p++] = utf8; sb[p++] = '";'; } function ser_array(a) { sb[p++] = 'a:'; var lp = p; sb[p++] = 0; sb[p++] = ':{'; for (var k in a) { if (typeof(a[k]) != 'function') { is_int(k) ? ser_integer(k) : ser_string(k); __serialize(a[k]); sb[lp]++; } } sb[p++] = '}'; } function ser_object(o) { var cn = classname(o); if (cn == '') ser_null(); else if (typeof(o.serialize) != 'function') { sb[p++] = 'O:' + cn.length + ':"'; sb[p++] = cn; sb[p++] = '":'; var lp = p; sb[p++] = 0; sb[p++] = ':{'; if (typeof(o.__sleep) == 'function') { var a = o.__sleep(); for (var kk in a) { ser_string(a[kk]); __serialize(o[a[kk]]); sb[lp]++; } } else { for (var k in o) { if (typeof(o[k]) != 'function') { ser_string(k); __serialize(o[k]); sb[lp]++; } } } sb[p++] = '}'; } else { var cs = o.serialize(); sb[p++] = 'C:' + cn.length + ':"'; sb[p++] = cn; sb[p++] = '":' + cs.length + ':{'; sb[p++] = cs; sb[p++] = "}"; } } function ser_pointref(R) { sb[p++] = "R:" + R + ";";