不少頁面用到的模態對話框,如知明網站https://dig.chouti.com/的登陸頁都是模態對話框,html
當點登陸時,是用的ajax提交,由於輸入錯了信息,有返回消息,而頁面沒有刷新。python
jquery ajax格式: jquery
$.ajax({
'url':'/orm',
'type':'post',
'data':{'id':1,'name':'hhh'},
success:function (data) {
alert(data);
}
})
url是提交到那個地址 type是提交方法 data是要提交的數據集合,可以使用變量如:$('#id').val(),可一句話提交一個表單裏的全部值 如:'data':$('#f1').serialize(),
sucess:是服務成功返回數據時要執行的函數,服務器沒返回數據時,這個函數不會執行,形參data,必定要帶,便是返回的數據。
提交給orm操做後 經常使用Httprespones返回一個字符串json格式,再用json解析 ,不能用redirect,用render也沒大用
這樣咱們在任何地方就能夠用ajax提交數據到後臺了,而頁面不用刷新,一個簡單標籤便可提交,如:
$('#ajax_submit').click(function () {
$.ajax({
'url':'/orm',
'type':'post',
'data':{'id':1,'name':'hhh'},
success:function (data) {
alert(data);
}
})
})
例子:點擊添加出現模態對話框,若是ip或端口格式不對,ajax提交當即返回錯誤提示不刷新。勾選1,3,5刪除一次性刪除並生效顯示。
#models from django.db import models # Create your models here. class host(models.Model): ip = models.CharField(max_length=255) port = models.IntegerField() group_code = models.ForeignKey(to='group',to_field='code',default='hr',on_delete='code') class group(models.Model): code = models.CharField(max_length=30,default='hr',unique=True) name = models.CharField(max_length=255) #views from django.shortcuts import render,HttpResponse,redirect from cmbd import models import json def home(request): return HttpResponse('<h1>home</h1>') def orm(request): # models.host.objects.create(ip="1.1.1.1",port=80,code='market') #models.host.objects.create(ip="1.1.1.6",port=88,group_code_id='dev') # models.group.objects.create(code="dev",name="開發部") # dic = {'code':'dep','name':"工程部"} # models.group.objects.create(**dic) if request.method == 'GET': cmd = request.GET.get('orm') if cmd == 'add_host': ip = request.GET.get('ip') port = request.GET.get('port') group_code = request.GET.get('group_code') if ip and port: models.host.objects.create(ip=ip,port=port,group_code_id=group_code) else: return HttpResponse('error') return redirect('/list') else: cmd = request.POST.get('orm') if cmd == 'del_host': host_id = request.POST.get('host_id') if host_id: models.host.objects.filter(id=host_id).delete() return HttpResponse('success') elif cmd == 'add_host': ip = request.POST.get('ip') port = request.POST.get('port') group_code = request.POST.get('group_code') if ip and port: models.host.objects.create(ip=ip,port=port,group_code_id=group_code) else: return HttpResponse('error') return HttpResponse('success') elif cmd == 'edit_host': id = request.POST.get('id') ip = request.POST.get('edit_ip') port = request.POST.get('edit_port') group_code = request.POST.get('edit_group_code') if ip and port: models.host.objects.filter(id=id).update(ip=ip,port=port,group_code_id=group_code) else: return HttpResponse('error') return redirect('/list') return render(request,'orm.html') def list(request): v1 = models.host.objects.all() v2 = models.group.objects.all() return render(request,'list.html',{'v1':v1,'v2':v2}) def test_ajax(request): ret = {"status":"true","data":"none","error":"none"} try: ip = request.POST.get('ip') port = request.POST.get('port') group_code = request.POST.get('group_code') if len(ip) < 4: ret["status"] = "false" ret["error"] = "ip addr error" except Exception as e: pass return HttpResponse(json.dumps(ret)) #templates <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> td a{ cursor: pointer; } .hide{ display: none; } .shade{ position: fixed; top:0; left:0; right:0; bottom:0; background-color: black; opacity:0.6; z-index: 99; } .add_model{ height:400px; width:600px; position: fixed; left: 50%; top: 50%; margin-left: -300px; margin-top: -200px; background-color: white; border: 1px solid greenyellow; z-index: 100; } </style> </head> <body> <div id="shade" class="shade hide"></div> <div id="add_model" class="add_model hide"> <form action="/orm" method="get" id="f1"> <table border="1px"> <thead><td>IP</td><td>端口</td><td>組別</td></thead> <tr> <td><input name="ip" type="text"/></td> <td><input name="port" type="text"/></td> <td> <select name="group_code"> {% for i in v2 %} <option value="{{ i.code }}">{{ i.name }}</option> {% endfor %} </select> </td> </tr> </table> <label id="msg" class="hide"></label> <input type="text" style="display: none;" name="orm" value="add_host"/> <input class="host_cancel" type="button" value="取消" style="position: absolute;bottom: 0;right: 123px;"/> <input id="add_host_ack" type="submit" value="肯定" style="position: absolute;bottom: 0;right: 0;"/> <input id="ajax_submit" type="button" value="ajax提交" style="position: absolute;bottom: 0;right: 50px;"/> </form> </div> <div id="edit_model" class="add_model hide"> <form action="/orm" method="post" id="f2"> <table border="1px"> <thead><td>IP</td><td>端口</td><td>組別</td></thead> <tr> <td><input name="edit_ip" type="text"/></td> <td><input name="edit_port" type="text"/></td> <td> <select name="edit_group_code"> {% for i in v2 %} <option value="{{ i.code }}">{{ i.name }}</option> {% endfor %} </select> </td> </tr> </table> <label id="edit_msg" class="hide"></label> <input type="text" class="hide" name="id"/> <input type="text" style="display: none;" name="orm" value="edit_host"/> <input class="host_cancel" type="button" value="取消" style="position: absolute;bottom: 0;right: 50px;"/> <input type="submit" value="肯定" style="position: absolute;bottom: 0;right: 0;"/> </form> </div> <h1>主機列表:</h1> <form> <input type="button" id="add_host" value="添加"> <input type="button" id="del_host" value="刪除"> <input type="button" id="select_all" value="全選"> <input type="button" id="cancel_all" value="取消"> <input type="button" id="revert" value="反選"> </form> <table border="1" id="t1"> <thead><td>選擇</td><td>序號</td><td>IP</td><td>端口</td><td>部門</td><td>操做</td></thead> {% for i in v1 %} <tr host_id="{{ i.id }}" group_code="{{ i.group_code_id }}"> <td><input type="checkbox"/></td> <td>{{ forloop.counter }}</td><td>{{ i.ip}}</td><td>{{ i.port}}</td><td>{{ i.group_code.name}}</td><td><a class="del_single">刪除</a>|<a class="edit_host">修改</a></td> </tr> {% endfor %} </table> <h1>組列表:</h1> <table border="1" id="t2"> <thead><td>序號</td><td>代碼</td><td>組名</td></thead> {% for i in v2 %} <tr group_id="{{ i.id }}"><td>{{ forloop.counter}}</td><td>{{ i.code}}</td><td>{{ i.name}}</td></tr> {% endfor %} </table> <script src="/static/jquery-3.3.1.js"></script> <script> $(function () { $('#add_host').click(function () { $("#shade,#add_model").removeClass("hide"); }) $('.host_cancel').click(function () { $(".shade,.add_model").addClass("hide"); }) $('#select_all').click(function () { $('#t1 input[type="checkbox"]').prop("checked", true); }) $('#cancel_all').click(function () { $('#t1 input[type="checkbox"]').prop("checked", false); }) $('#revert').click(function () { $('#t1 input[type="checkbox"]').each(function () { if($(this).prop('checked')){ $(this).prop('checked',false); }else { $(this).prop('checked',true); } }); }) $('#del_host').click(function () { $('#t1 input[type="checkbox"]').each(function () { if($(this).prop('checked')){ host_id = $(this).parent().parent().attr('host_id'); $.ajax({ 'url':'/orm', 'type':'post', 'data':{'orm':'del_host','host_id':host_id}, success:function (data) { console.log(data); location.reload(); } }) } }); }) $('#ajax_submit').click(function () { $.ajax({ 'url':'/test_ajax', 'type':'post', 'data':$("#f1").serialize(), success:function (data) { obj = JSON.parse(data) if(obj.status=='true'){ $('#msg').removeClass('hide').text(obj.data); location.reload(); }else { $('#msg').removeClass('hide').text(obj.error); } } }) }) $(".del_single").click(function () { host_id = $(this).parent().parent().attr('host_id'); $(this).parent().parent().remove(); $.ajax({ 'url':'/orm', 'type':'post', 'data':{'orm':'del_host','host_id':host_id}, success:function (data) { alert(data); } }) }) $(".edit_host").click(function () { group_code = $(this).parent().parent().attr('group_code'); host_id = $(this).parent().parent().attr('host_id'); ip = $(this).parent().parent().children().eq(2).text(); port = $(this).parent().parent().children().eq(3).text(); console.log(host_id,ip,port); $("#shade,#edit_model").removeClass("hide"); $("#f2 select[name='edit_group_code']").val(group_code); $("#f2 input[name='edit_ip']").val(ip); $("#f2 input[name='edit_port']").val(port); $("#f2 input[name='id']").val(host_id); }) }) </script> </body> </html>