json数据在前端遍历注意事项

来源:互联网 发布:linux sys.h 编辑:程序博客网 时间:2024/05/16 05:45

方法一:使用jquery

$.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>");});}});
方法二:使用eval()

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(); }
注意:{"age":1,"id":1,"name":"zxc"}是json返回数据的格式,key带有引号“” ,需要用eval()函数转成{age:1,id:1,name:"zxc"}格式,才能用for循环在js中遍历



原创粉丝点击