Ajax增刪改查實例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>

<div align="center">


<tr><td><button onclick='list()'>查看列表</button></td></tr>
<tr><td><button onclick='add()'>添加</button></td></tr>
<table  border="1">
<tr>
<td>編號</td>
<td>姓名</td>
<td>操作</td>
<td>操作</td>
</tr>


</table>
<table id="tt" border="1"></table>

<!-- //更新回顯 -->
</div >
<div id="dd" style="display: none;" align="center">
id:<input type="text" id="id"><br>
姓名:<input type="text" id="name"><br>
<button onclick="update()">更新</button>
</div>

<!-- //添加 -->
</div >
<div id="ff" style="display: none;" align="center">
id:<input type="text" id="addid"><br>
姓名:<input type="text" id="addname"><br>
<button onclick="save()">保存</button>
</div>

<script type="text/javascript">
function list(){
	
	
	$.ajax({
		
		url:"a?method=findlist",
		type:"get",
		data:"",
		dataType:"json",
		success:function(list){
		
			for(var i in list){
		  		$("#tt").append("<tr><td>"+list[i].id+"</td><td>"+list[i].name+
		  				"</td><td><button onclick='toupdate("+list[i].id+")'>更新</button></td>"+
		  				"</td><td><button onclick='todelete("+list[i].id+")'>刪除</button></td></tr>"
		  		)
		  	}
		}
		
		
	});
  
}

function toupdate(id) {
	$.ajax({
		
		url:"a?method=toupdate",
		type:"post",
		data:"id="+id,
		dataType:"json",
		
		success:function(user){
			$("#dd #id").val(user.id);
			$("#dd #name").val(user.name);
			$("#dd").show();
		}
	});
}

function update(id) {
	var id = $("#id").val();
	var name =$("#name").val();
	$.ajax({
		
		url:"a?method=update",
		type:"post",
		data:{"id":id,"name":name},
		dataType:"json",
		contentType:'application/x-www-form-urlencoded;charset=UTF-8',
		success:function(data){
			if(data=="success"){
				alert("更新失敗");
			}else{
				alert("更新成功");
				window.location.href = window.location.href;
			}
			
		}
	});
	
	$("#dd").hide();
	
}


	 
	

	


function add() {
	$("#ff").show();
}


function save() {
	var id =$("#addid").val();
	var name =$("#addname").val();
	$.ajax({
		
		url:"a?method=save",
		type:"post",
		data:{"name":name,"id":id},
		dataType:"json",
		success:function(data){
			if(data=="success"){
				alert("添加失敗");
			}else{
				alert("添加成功");
				window.location.href = window.location.href;
			}
			
		}
	});
	
	
	$("#dd").hide();
}

</script>

<script>
function todelete(id) {
	$.ajax({
		url:"a?method=delete",
		type:"post",
		data:"id="+id,
		dataType:"json",
		success:function(data){
			if(data=="success"){
				alert("刪除失敗");
			}else{
				alert("刪除成功");
				window.location.href = window.location.href;
			}	
		}
	});
}
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章