json学习笔记

今天仔细学习了一下json。以下是代码的总结。

ie不支持JSON.parse(将字符串改为object对象)和JSON.stringify(将object对象转为字符串),

所以要用eval ()方法或JSON2.js。

test3.json(就是txt改个后缀名,我被它唬住了)

{ "firstName":"Bill" , "lastName":"Gates" }


index.html

<html>
<head>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
function loadXMLDoc(){
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.open("GET","test3.json",false);
    xmlhttp.send();
    //没有用json2.js时,ie不支持JSON.parse
    //    if (typeof (JSON) == 'undefined')     
    //    {
    //        aaa=eval ((new Function("return "+xmlhttp.responseText))());
    //    }
    //    else     
    //    {
    //        aaa=JSON.parse(xmlhttp.responseText);
    //    }
            aaa=JSON.parse(xmlhttp.responseText);
    alert(aaa.firstName)
    document.getElementById('myDiv').innerHTML=JSON.stringify(aaa);
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onClick="loadXMLDoc()">通过 AJAX 改变内容</button>

</body>
</html>

json2.js的下载地址:

https://github.com/douglascrockford/JSON-js

w3school的学习地址:

http://www.w3school.com.cn/json/json_eval.asp

以下是广告:————————————————————————————————————————

原文地址:https://www.cnblogs.com/cssfirefly/p/2710543.html