Ajax
应用场景:我们在输入表单进行提交的时候往往会判断输入的数据形式是否正确,这个时候如果我们点击了提交就会刷新页面。如果我们不想要它刷新页面,让它“悄悄的提交数据”,这个时候我们就需要使用ajax。
ajax格式:
$.ajax({ url:'/host', type:"POST", data:{'k1':'v1','k2':'v2'}, success:function(data):{ if(data == 'lkdfa'){ location.reload();#刷新页面 }else{ alert(data); } } })
上面的data是服务器端返回的字符串
一般我们服务器端会把数据以字典转换成字符串的形式传给前端,如:在python中用json.dumps把字典转换成字符串
ret = {'status':True,'data':None,'error':None} try: hostname = request.POST.get('hostname') ip = request.POST.get('ip') port = request.POST.get('port') b_id = request.POST.get('b_id') print(request.method, hostname, ip,port,b_id,sep='\t') if hostname and len(hostname) > 3: models.Host.objects.create( hostname=hostname, ip=ip, port=port, b_id=b_id, ) else: ret['status'] = False ret['error'] = "your hostname is too short" except Exception as e: ret['status'] = False ret['error'] = "请求错误" return HttpResponse(json.dumps(ret))
我们在前端就需要用到JSON.parse(data)把字符串转换成字典(在把字典转换成字符串要用JSON.stringify())
当然还可以用一个简单的方法获得表单中所有的数据:
data: $('#opt_form').serialize(),#opt_form是表单的id选择器的名称
如果我们嫌处理data麻烦,每次都要用json.parse()转换数据的话,可以用下面的:
$.ajax({
url : '/ajax_add_app',
data:{'user':123,'pwd':456},
type:'POST',
traditional:true,
dataType:'JSON',
success:function(obj){
},
error:function(){},
})
那下面function里面的参数就不是一个字符串,而是一个对象
error:我们发了一个未知的错误,后台没有捕捉到,才会执行
traditional:默认是false,如果表单得到的数据是一个列表,默认是后台是接收不到的,如果设置成了true,后台用getlist()就可以了
实例:对表格数据的增删改查:
html文件:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .hide{ 8 display: none; 9 } 10 .shade{ 11 position: fixed; 12 top:0; 13 left:0; 14 right:0; 15 bottom: 0; 16 background-color: black; 17 opacity: 0.6; 18 z-index: 9; 19 } 20 .add_model{ 21 position: fixed; 22 height:300px; 23 width:400px; 24 top:50%; 25 left:50%; 26 z-index: 10; 27 border: 1px solid red; 28 background-color: white; 29 margin-top: -150px; 30 margin-left:-200px; 31 } 32 .ajax_submit{ 33 display: inline-block; 34 padding:5px; 35 background-color: blue; 36 color:white; 37 } 38 </style> 39 </head> 40 <body> 41 <h1>主机列表</h1> 42 <div> 43 <input id="add_host" type="button" value="添加" /> 44 </div> 45 <table border="1"> 46 <thead> 47 <tr> 48 <th>序号</th> 49 <th>主机名</th> 50 <th>ip</th> 51 <th>端口</th> 52 <th>业务线名称</th> 53 <th>操作</th> 54 </tr> 55 </thead> 56 <tbody> 57 {% for row in v1 %} 58 <tr nid="{{ row.nid }}" bid="{{ row.b_id }}"> 59 <td>{{ forloop.counter }}</td> 60 <td id="h">{{ row.hostname }}</td> 61 <td id="i">{{ row.ip }}</td> 62 <td id="p">{{ row.port }}</td> 63 <td>{{ row.b.caption }}</td> 64 <td><a class="edit">修改</a>丨<a class="del">删除</a></td> 65 </tr> 66 {% endfor %} 67 </tbody> 68 </table> 69 <div class="hide shade"></div> 70 <div class="hide add_model"> 71 <form id="opt_form" action="/host/" method="post"> 72 <div class="group" style="display: none;"> 73 <p>用户id:<input id="nid" type="text" name="nid" /></p> 74 </div> 75 <div class="group"> 76 <p>主机名:<input id="hostname" type="text" name="hostname" /></p> 77 </div> 78 <div class="group"> 79 <p>IP:<input id="ip" type="text" name="ip" /></p> 80 </div> 81 <div class="group"> 82 <p>端口:<input id="port" type="text" name="port" /></p> 83 </div> 84 <div class="group"> 85 <p> 86 业务线: 87 <select id="se1" name="b_id"> 88 {% for row in b_list %} 89 <option value="{{ row.id }}">{{ row.caption }}</option> 90 {% endfor %} 91 </select> 92 </p> 93 </div> 94 <a id="ajax_submit" class="ajax_submit">ajax提交</a> 95 <input id="cancel" type="button" value="取消" /> 96 <span id="error_msg" style="color:red"></span> 97 </form> 98 99 </div> 100 101 <script src="/static/jquery-1.12.4.js"></script> 102 <script> 103 $(function(){ 104 $('#add_host').click(function(){ 105 $('.shade,.add_model').removeClass('hide'); 106 }); 107 $('#cancel').click(function(){ 108 $('.shade,.add_model').addClass('hide'); 109 }); 110 $('#ajax_submit').click(function(){ 111 $.ajax({ 112 url : '/test_ajax/', 113 type:'POST', 114 data: $('#opt_form').serialize(), 115 success:function (data) { 116 var obj = JSON.parse(data) 117 if(obj.status){ 118 location.reload() 119 }else{ 120 $('#error_msg').text(obj.error); 121 } 122 } 123 }) 124 }); 125 $('.edit').click(function(){ 126 $('.shade,.add_model').removeClass('hide'); 127 128 var hostname = $(this).parent().parent().find('#h').text() 129 var ip = $(this).parent().parent().find('#i').text() 130 var port = $(this).parent().parent().find('#p').text() 131 var nid = $(this).parent().parent().attr('nid') 132 var bid = $(this).parent().parent().attr('bid'); 133 134 $('#nid').val(nid); 135 $('#hostname').val(hostname); 136 $('#ip').val(ip); 137 $('#port').val(port); 138 $('#se1').val(bid); 139 140 }); 141 $('.del').click(function(){ 142 var nid = $(this).parent().parent().attr('nid') 143 var hostname = $(this).parent().parent().find('#h').text() 144 145 var result = confirm("确定要删除主机名为"+hostname+"的记录吗?") 146 147 if(result){ 148 149 $.ajax({ 150 url : '/delete/', 151 type : 'POST', 152 data : {'nid':nid}, 153 success:function(data){ 154 alert(data) 155 } 156 }); 157 $(this).parent().parent().addClass('content') 158 $(this).parent().parent().parent().find('.content').html("<span style='color:red;align-text:left'>已经删除</span>") 159 } 160 }); 161 }); 162 </script> 163 </body> 164 </html>
url.py:
from django.contrib import admin from django.urls import path from django.conf.urls import url,include from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^business/$',views.business), url(r'^host/$',views.host), url(r'^test_ajax/$',views.test_ajax), url(r'^delete/$',views.delete), ]
view.py:
from django.shortcuts import render,redirect,HttpResponse from app01 import models import json # Create your views here. def business(request): v = models.Business.objects.all() return render(request,'business.html',{'v':v}) def host(request): if request.method=='GET': v1 = models.Host.objects.filter(nid__gt=0) b_list = models.Business.objects.all() return render(request, 'host.html', {'v1': v1,'b_list':b_list}) elif request.method=='POST': hostname = request.POST.get('hostname') ip = request.POST.get('ip') port = request.POST.get('port') b_id = request.POST.get('b_id') models.Host.objects.create( hostname=hostname, ip=ip, port=port, b_id=b_id, ) return redirect('/host') def test_ajax(request): ret = {'status':True,'data':None,'error':None} try: nid = request.POST.get('nid') hostname = request.POST.get('hostname') ip = request.POST.get('ip') port = request.POST.get('port') b_id = request.POST.get('b_id') print(request.method, nid ,hostname, ip,port,b_id,sep='\t') if hostname and len(hostname) > 3: if nid : models.Host.objects.filter(nid=nid).update( hostname=hostname, ip=ip, port=port, b_id=b_id, ) else: models.Host.objects.create( hostname=hostname, ip=ip, port=port, b_id=b_id, ) else: ret['status'] = False ret['error'] = "your hostname is too short" except Exception as e: ret['status'] = False ret['error'] = "请求错误" return HttpResponse(json.dumps(ret)) def delete(request): nid = request.POST.get('nid') print(nid) result = models.Host.objects.filter(nid = nid).delete() if result: return HttpResponse('ok') else: return HttpResponse('fail to delete data')
model.py:
from django.db import models # Create your models here. class Business(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=32,null=True,default='SA') class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32,db_index=True) ip = models.GenericIPAddressField(protocol='ipv4',db_index=True) port = models.IntegerField() b = models.ForeignKey(to='Business',to_field='id',on_delete=models.CASCADE)