jQuery Ajax 解析json格式

本文由清尘发表于2014-02-16 16:19最后修改于2014-12-16属于jQuery分类

HTML部分:

<style type="text/css">
.btn{background-color:#ccc; border:1px solid #ccc; cursor:pointer;}
#ctn{width:600px; height:300px; border:1px solid #000;}
</style>
<span class="btn">get ajax</span>
<div id="ctn"></div>

JS代码:

$(function(){
			$(".btn").click(function(){
				$.ajax({
					url:"ajaxtest.json",
					cache:false,
					success:function(data){
						var ctn_html="";
						$.each(data.employees,function(i,n){
							var firstName=data.employees[i].firstName;
							var lastName=data.employees[i].lastName;
							ctn_html+=firstName+":"+lastName+"<br/>";
						});
						$("#ctn").html(ctn_html);
					},
				});
			});
		})

上例所用 ajaxtest.json 文件内容:

{
"employees":[
	{"firstName":"John","lastName":"Doe"},
	{"firstName":"Anna","lastName":"Smith"},
	{"firstName":"Peter","lastName":"Jones"}
]
}

jQuery Ajax 解析json格式