1.json格式:{"naU":[{"number":"111","names":"pengpeng"}]} a.txt
javascript代码:
if (window.xmlhttprequest) { var xmlrequest = new window.xmlhttprequest(); } else { var xmlrequest = new ActiveXObject("microsoft.xmlhttp"); } var url = "a.txt?t=" + new Date().getDate(); xmlrequest.open("GET", url, true); xmlrequest.onreadystatechange = function () { if (xmlrequest.readystate == 4 && xmlrequest.status == 200) { var result = xmlrequest.responsetext; var json = eval("("+result+")"); alert(json.naU[0].number) //111 //alert(xmlrequest.responsetext+ "show"); } } xmlrequest.send(null);
2. {"naU":[{"number":"V006","names":"LiLei"},{"number":"V007","names":"meimei"},{"number":"V008","names":"LiLei"}]}
使用$.ajax()方法实现:
$.ajax({ type: "GET", contentType:"application/json", url:"aaa.txt", dataType: 'json', success: function (data) { alert(data.naU[1].number);//Voo6 $("body").append("<div>" + data + "</div>").css("color","red"); }, error:function(){ alert("the function have a problem"); } })
3.使用$.get()方法获取:
$.get("aaa.txt",function(data){ var json =eval( "(" + data + ")"); $("body").append("<div>" + json.naU[1].number + "</div>").css("color", "red");//Voo7 }) })
//data还是json格式的字符串,需要用eval()进行转换