//声明对象实例 var xmlhttp = false; //产生一个XMLHttpRequest对象实例 getHTTPRequestObject(); function getHTTPRequestObject() { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(E) { xmlhttp = false; } } if(!xmlhttp && typeof XMLHttpRequest!= 'undefined') { xmlhttp = new XMLHttpRequest(); } } //回调处理 function callback() { if(xmlhttp.readyState == 4) { if(xmlhttp.status == 200) { // 转换Json数据为javascript对象 eval("var objResults =" + xmlhttp.responseText); var displaytext = ""; for (var i=0; i < objResults.Results.computer.length; i++) { displaytext += objResults.Results.computer[i].Manufacturer + " " + objResults.Results.computer[i].Model + ": $" + objResults.Results.computer[i].Price + "<br>"; } var finddiv = document.getElementById("divResponse");//寻找显示容器 finddiv.innerHTML = displaytext;//引用解析好了的数据 } } } //触发事件 function btnClick() { // retrieve the JSON text from the local file. xmlhttp.open("GET", "JSON.txt", true); xmlhttp.onreadystatechange = callback; xmlhttp.send(null); }
JSON.txt 内容:
{"Results": { "total_computers": "2", "computer": [ { "Manufacturer":"Dell", "Model":"Latitude", "Price":"1650" }, { "Manufacturer":"Dell", "Model":"Inspiron", "Price":"1850" } ] } }