1.简单的json格式
{ "user": [ { "name":"name1", "age":24, "sex":"男" }, { "name":"name2", "age":24, "sex":"男" }, { "name":"name3", "age":24, "sex":"男" } ] }
2.完整的Ajax调用
<script type="text/javascript"> function GetMessageByUrl() { $.ajax({ type: "GET", cache: "false", // url: "http://192.168.1.132:890/api/vehicle/tracking", url: "TextJson.txt", datatype: "json", success: function (data) { /// ///通过eval()将json格式字符串转换成json对象。 /// var dataEval = eval("(" + data + ")"); alert(dataEval.user[1].name); alert("节点1"); /// ///通过$.parseJSON()将json格式字符串转换成json对象。 /// var dataObj = jQuery.parseJSON(data); alert(dataObj.user[2].name); alert("节点2"); /// ///遍历json对象中的元素 /// $.each(dataObj.user, function (idx, item) { alert("name:" + item.name + ",value:" + item.age); }) }, error: function (err_data) { alert(err_data); } }) }; </script>
3.简单调用
var txt = '{"employees":[' + '{"firstName":"Bill","lastName":"Gates" },' + '{"firstName":"George","lastName":"Bush" },' + '{"firstName":"Thomas","lastName":"Carter" }]}'; var obj = eval("(" + txt + ")"); document.getElementById("fname").innerHTML = obj.employees[1].firstName document.getElementById("lname").innerHTML = obj.employees[1].lastName $.each(obj.employees, function (idx, item) { if (idx == 0) { return true; //同countinue,返回false同break } alert("name:" + item.firstName + ",value:" + item.lastName); });