<div class="codetitle"> <span><a style="CURSOR: pointer" data="2483" class="copybut" id="copybut2483" onclick="doCopy('code2483')"><u>複製代碼</u></a></span> 代碼如下:</div> <div class="codebody" id="code2483"> <br>//W3C/1. Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br> <br> <br><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <br><meta name="author" content=" Nancle from CAU CS 101"> <br><title>JSON序列化與解析(原生JS Object物件拓展方法)【IE6與chrome測試通過】</title> <br> <br><script type="text/javascript"> <BR>var ele = { <BR>x:11, <BR>y:'string', <BR>z:{x:11, y:'string'} <BR> } <BR>toJSON = function(obj){ <BR>var arr = []; <BR>for(var key in obj){ <BR>var value = obj[key]; <BR>if(value == null){ <BR>value = ''; <BR>}else{ <BR>value = (typeof value === 'string' | typeof value === 'number') <BR>? ('"' value '"') : toJSON(value); <BR>} <BR>var str = '"' key '":' value; <BR>arr.push(str); <BR>} <BR>return '{ ' arr.join(',') '}'; <BR>} <BR>var str = toJSON(ele); <BR>alert('裝換成的字串是: ' str ); <BR>var ele2 = eval('(' str ')'); <BR>alert('解析字串得到js物件: x=' ele2.x ',y=' ele2.y ',z=' ele2.z); <BR></script> <br> <br> <br> <br> </div>