(五)AJAX技术

一、定义

  • AJAX 是一种用于创建快速动态网页的技术。
  • 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
  • 传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个网页页面。

 

 

 


<script type="text/javascript" src="./js/lib/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('button').click(function(){show();});
	});
	function show(){
		$.getJSON("./source/student.json",function(stu){           //在“./source/student.json”
									        //地址里找到文件,然后调用函数,stu为这个文件对象
			
				$("#tab").empty();                 //防止多次刷新出现重复值,即每次点击按钮之后会先清空表格里的内容
				$('#tab').append("<tr><td>"+stu.name+"</td><td>"+stu.age+"</td></tr>");   
		});
	}
</script>
</head>
<body>
	<button>点我刷新数据</button>
	<table>
		<tr>
			<th>姓名</th>
			<th>年龄</th>
		</tr>
	</table>
	<table style="border-style:solid;width:150px;height:20px;" id="tab">
		
		<tr>
			<td></td>
			<td></td>
		</tr>
	</table>
</body>

  

 student.json:

    {"name":"张三","age":"15"}

 

结果:

 


ps:如果json文件里只有一个对象,即{“name”:"张三","age","15"} 则不用each循环即可获取数据,即

function(stu){//stu.name,stu.age取值}

如果是json文件里有不止一个对象,即【{“name”:"张三","age","15"},{“name”:"李四","age","16"}】

注意一定要加大括号,一定要用each循环才能读取数据,如果只有一个对象加了大括号也被当成多个对象。

 

<script type="text/javascript" src="./js/lib/jquery.js"></script>
<script type="text/javascript">
	$(function(){
		$('button').click(function(){show();});
	});
	function show(){
		$.getJSON("./source/student.json",function(stu){ //在“./source/student.json”
									
			
				$("#tab").empty();   
				$.each(stu,function(i,n){
					$('#tab').append("<tr><td>"+n.name+"</td><td>"+n.age+"</td></tr>");
					
				});
				
		});
	}
</script>
</head>
<body>
	<button>点我刷新数据</button>
	<table>
		<tr>
			<th>姓名</th>
			<th>年龄</th>
		</tr>
	</table>
	<table style="border-style:solid;width:150px;height:20px;" id="tab">
		
		<tr>
			<td></td>
			<td></td>
		</tr>
	</table>
</body>

 结果:

 

posted @ 2017-02-28 20:04  shyroke、  阅读(155)  评论(0编辑  收藏  举报
作者:shyroke 博客地址:http://www.cnblogs.com/shyroke/ 转载注明来源~