django通過ajax將後臺json數據返回到前臺table中顯示

def findinfo(request):
	return render(request,'findinfo.html')

def findresult(request):
	id = request.GET['id']
	items = []
	testline = {}

	cursor = connection.cursor()

	if (id == ""):
		cursor.execute("SELECT id,name from tmp_info")
	else:
		cursor.execute("SELECT id,name from tmp_info where id ='" + id + "'")
    
	rows = cursor.fetchall()
	for row in rows:
		testline['id'] = row[0]
		testline['name'] = row[1]
		items.append(testline.copy())
	cursor.close()
	
	return HttpResponse(str(items))				#直接返回數據

 

findinfo.html

<!DOCTYPE html>
<html>
<head>
	<title>用戶查詢頁面(nxy)</title>
</head>
<body>

<form align="center" action="/findresult/" method="get">
查詢編號: <input type="text" id="id" name="id"> <br><br>
	
	<button  type="button" id='find'>查詢</button>
	&nbsp; &nbsp; &nbsp; &nbsp; 
	<button  type="button" id='chongzhi' onclick="document.getElementById('id').value=''">重置</button>
</br></br>

</form>

<table class="gridtable" align="center" id="pstable" border="1">
<thead>
            <tr>
                <th align=center width=100>編號</th>
                <th align=center width=200>姓名</th>
				<th align=center width=200>處理</th>
            </tr>
</thead>

<tbody>
</tbody>

</table>


<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
	$(document).ready(function(){
		$("#find").click(function(){
		var id = $("#id").val();
		
		
		
		$.get("/findresult/",{'id':id}, function(ret){
			
			var obj = eval(ret);
			
			var tbody=$('<tbody></tbody>');
			
			
			for(var i=0;i<obj.length;i++){
				var tr=$('<tr></tr>');
				tr.append('<td>'+ obj[i]['id'] + '</td>' + '<td>'+ obj[i]['name'] + '</td>' +'<td><a href="/delete?id=' + obj[i]['id'] + '" >刪除數據</a></td>' );
				tbody.append(tr);
			}
			
			$('#pstable tbody').replaceWith(tbody);
        })
      });
    });
</script>

</body>
</html>





<style type="text/css">
  table.gridtable {
      font-family: verdana,arial,sans-serif;
      font-size:11px;
      color:#333333;
      border-width: 1px;
      border-color: #666666;
      border-collapse: collapse;
 }
 table.gridtable th {
     border-width: 1px;
     padding: 8px;
     border-style: solid;
     border-color: #666666;
     background-color: #dedede;
 }
 table.gridtable td {
     border-width: 1px;
     padding: 8px;
     border-style: solid;
     border-color: #666666;
     background-color: #ffffff;
 }
 </style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章