zoukankan      html  css  js  c++  java
  • 在JavaScript中使用json.js:使得js数组转为JSON编码

    在json的官网中下载json.js,然后在script中引入,以使用json.js提供的两个关键方法。

    1、数组对象.toJSONString()

    这个方法将返回一个JSON编码格式的字符串,用来表示类型中的数据。

    演示:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    	<head>
            <script type="text/javascript" src="json.js"></script>
            <script type="text/javascript">
                function showJsonData(){
                    original= new Array(0,1,2,3);
                    
                    //在JSON中编码原始值并返回一个字符串
                    json= original.toJSONString();
                    
                    div=document.getElementById("jsonData");
                    div.innerHTML=json;
                }
            </script>
    	</head>
    	<body>
    		<a href="#" onclick="showJsonData()">Show JSON Data</a>
            <div id="jsonData"></div>
    	</body>
    </html>
    

    输出结果:[0,1,2,3]

    2、JSON编码.parseJSON()

    这个方法可以将JSON编码的字符传恢复为JavaScript结构(如:数组)。

    演示:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    	<head>
            <script type="text/javascript" src="json.js"></script>
            <script type="text/javascript">
                function showJsonData(){
                    original= new Array("hgykb","SDHFI");
                    
                    //在JSON中编码原始值并返回一个字符串
                    json= original.toJSONString();
                    
                    div=document.getElementById("jsonData");
                    
                    //解码JSON数据,并将数组中的第一个元素设置到div.innerHTML属性上
                    div.innerHTML=json.parseJSON()[0];
                }
            </script>
    	</head>
    	<body>
    		<a href="#" onclick="showJsonData()">Show JSON Data</a>
            <div id="jsonData"></div>
    	</body>
    </html>
    

    输出结果:hgykb

  • 相关阅读:
    第五周学习总结
    第四周学习总结
    实验三报告
    第2,3周学习总结
    第二次实验报告
    实验一报告
    MyFirstStruts2
    java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
    Tomcat version 6.0 only supports J2EE 1.2, 1.3, 1.4,and Java EE 5 Web modules
    The JRE could not be found.Edit the server and change the JRE location.
  • 原文地址:https://www.cnblogs.com/andy9468/p/4242713.html
Copyright © 2011-2022 走看看