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

方法一:使用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中遍历



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值