ajax+json

今天是平安夜,花了点时间研究了一下Jquery ajax和json数据的获取。感觉学习到了蛮多。本次的页面是假设在xampp上的。PS:悲催的发现xampp的端口被之前的everything端口占用了,现在用的端口是88 和444端口。背景交代完毕,进入正文。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
	<title>ajax_demo</title>
	<style type="text/css">
.table{float:left;border: 1px solid black;margin:0 auto;width: 500px;height: 500px;}
li{list-style-type: none;width: 300px;height: 40px;border: 1px solid red;}
	</style>
	<script src="http://img.jb51.net/jslib/jquery/jquery.js" type="text/javascript"></script> 
</head>
<body>
<div class="table">
	<ul>
		<li>您的姓名是:</li>
		<li>您的年龄是:</li>
	</ul>
</div>
<button>ajax()</button>

<script type="text/javascript">
	$(document).ready(function(){
	
		$("button").one("click",function(){  //使用one是为了防止重复点击按钮后不停加载数据
			$.ajax({
				type:'post',
				dataType:'json',
				url:'demo/demo.json',
				success:function(data){
	//alert(data);
$.each(data,function(i,obj){     //使用each方法循环遍历获取到的json数据
	var nameNum=obj.name.length 
	var name=obj.name; 
	var age=obj.age;
	switch(i){
		case 0: $(".table ul li").eq(0).append(name);
				$(".table ul li").eq(1).append(age);
				break;
		//case 1: $(".table ul li").eq(0).append(name);
		//		$(".table ul li").eq(1).append(age);
		//		break;
		//case 2 :$(".table ul li").eq(0).append(name);
		//		$(".table ul li").eq(1).append(age);
		//		break;
	}
//$(".table ul li").eq(0).append(name);
//$(".table ul li").eq(1).append(obj.age);
});
			},error:function(XMLHttpRequest,textStatus,errorThrown){
				alert(errorThrown);
			}

		});
		});
	});
</script>
</body>
</html>
json数据
[
{
	'name':'desmond',
	'age':'111'
},
{
	'name':'liu',
	'age':'1231'
},
{
	'name':'jj',
	'age':'211'
}
]


你可能感兴趣的:(jquery,Ajax,+json)