json資料在前端遍歷注意事項
阿新 • • 發佈:2019-02-15
方法一:使用jquery
方法二:使用eval()$.ajax({ type : "POST" , async : true, url :"${pageContext.request.contextPath}/JqueryAjaxDemo", data : {"id" : 123 , "name" : "zxc"}, //傳遞引數 dataType : "json", //規定了返回型別 也可以不規定 直接$.each($.parseJSON(result),function(id,json){}); error : function(){alrt('error');}, success : function(result){ $.each(result,function(id,json){ $("#ajax2").append(id+json.id+json.name+json.age); $("#ajax3").html("<h1>hello</h1>"); $("#ajax4").text("<h1>hello</h1>"); }); } });
注意:{"age":1,"id":1,"name":"zxc"}是json返回資料的格式,key帶有引號“” ,需要用eval()函式轉成{age:1,id:1,name:"zxc"}格式,才能用for迴圈在js中遍歷var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200){ //返回值格式 {"age":1,"id":1,"name":"zxc"} 注意 不是{fname:"John",lname:"Doe",age:25}這種格式 var json = eval('('+xmlhttp.responseText+')'); for(var x in json ){ alert(json[x]); } document.getElementById("ajax1").innerHTML =json.id+json.name+json.age; } } xmlhttp.open("get","${pageContext.request.contextPath}/AjaxDemo_json?"+Date(),true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(); }