Django-website 程序案例系列-6 ajax案例
普通ajax案例:
views.py
def testajax(request): h = request.POST.get('hostname') #拿到ajax传来的值 i = request.POST.get('ip') p = request.POST.get('port') b = request.POST.get('b_id') if h and len(h) < 5: #如果为空和长度小于5 models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) #存入主机表信息 return HttpResponse('OK') #存入成功返回‘OK’ else: return HttpResponse('fail') #不成功返回‘fail’
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .shade{ position: fixed; top: 0; right: 0; left: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal{ position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid black; background: white; margin-left: -200px; } </style> </head> <body> <h1>主机信息</h1> <div> <input type="button" id="add_host" value="添加"/> </div> <table border="1"> <thead> <tr> <th>序号</th> <th>主机名</th> <th>IP</th> <th>端口</th> <th>业务线ID</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr host-id="{{ row.id }}" bid="{{ row.b_id }}"> <td>{{ forloop.counter }}</td> <td>{{ row.hostname }}</td> <td>{{ row.ip }}</td> <td>{{ row.port }}</td> <td>{{ row.b_id }}</td> <td>{{ row.b.caption }}</td> </tr> {% endfor %} </tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form action="/host" method="POST"> <div class="group"> <input type="text" id="host" placeholder="主机名" name="hostname"/> </div> <div class="group"> <input type="text" id="ip" placeholder="IP" name="ip"/> </div> <div class="group"> <input type="text" id="port" placeholder="端口" name="port"/> </div> <div class="group"> <select id="sel" name="b_id"> {% for op in b_list %} <option value="{{ op.id }}">{{ op.caption }}</option> {% endfor %} </select> </div> <input type="submit" value="提交"/> <input type="button" id="cancel" value="取消"/> </form>
# ajax提交按钮,id为ajax_submit在JS中进行判断 <input type="button" value="ajaxtijiao" id="ajax_submit" style="display: inline-block;padding: 5px;background: blue;color: black;"/> </div> <script src="static/js/jquery.min.js"></script> <script> $(function() { $('#add_host').click(function(){ $('.shade,.add-modal').removeClass('hide'); }); $('#cancel').click(function(){ $('.shade,.add-modal').addClass('hide'); }); }) $('#ajax_submit').click(function(){ #判断标签‘ajax_submit’的ajax提交事件 $.ajax({ url: "/testajax", #提交的url type: "POST", #提交方式 POST|GET data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(),'b_id': $('#sel').val()}, #提交的数据 success: function(data) { #返回的函数 if(data == "OK"){ #如果返回OK location.reload(); #重新加载本网页(刷新) }else{ alert(data); #不然返回一个弹出框 } } }) }) </script> </body> </html>
ajax回传json数据:
views.py
def testajax(request): import json #导入json包 ret = {'status': True, 'error': None, 'data': None} #json格式的字符串序列 try: #使用try来捕获错误 h = request.POST.get('hostname') i = request.POST.get('ip') p = request.POST.get('port') b = request.POST.get('b_id') if h and len(h) > 5: models.Host.objects.create( hostname=h, ip=i, port=p, b_id=b) else: ret['status'] = False #往字符串中写入错误字段 ret['error'] = "太短了" except Exception as e: #报错字段 ret['status'] = False #往字符串中写入错误字段 ret['error'] = "请求错误" return HttpResponse(json.dumps(ret)) #使用json工具把json格式转换成为字符串
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .shade{ position: fixed; top: 0; right: 0; left: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal{ position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid black; background: white; margin-left: -200px; } </style> </head> <body> <h1>主机信息</h1> <div> <input type="button" id="add_host" value="添加"/> </div> <table border="1"> <thead> <tr> <th>序号</th> <th>主机名</th> <th>IP</th> <th>端口</th> <th>业务线ID</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr host-id="{{ row.id }}" bid="{{ row.b_id }}"> <td>{{ forloop.counter }}</td> <td>{{ row.hostname }}</td> <td>{{ row.ip }}</td> <td>{{ row.port }}</td> <td>{{ row.b_id }}</td> <td>{{ row.b.caption }}</td> </tr> {% endfor %} </tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form action="/host" method="POST"> <div class="group"> <input type="text" id="host" placeholder="主机名" name="hostname"/> </div> <div class="group"> <input type="text" id="ip" placeholder="IP" name="ip"/> </div> <div class="group"> <input type="text" id="port" placeholder="端口" name="port"/> </div> <div class="group"> <select id="sel" name="b_id"> {% for op in b_list %} <option value="{{ op.id }}">{{ op.caption }}</option> {% endfor %} </select> </div> <input type="submit" value="提交"/> <input type="button" id="cancel" value="取消"/> </form> <input type="button" value="ajaxtijiao" id="ajax_submit" style="display: inline-block;padding: 5px;background: blue;color: black;"/>
<span id="error_msg" style="color: red"></span> </div> <script src="static/js/jquery.min.js"></script> <script> $(function() { $('#add_host').click(function(){ $('.shade,.add-modal').removeClass('hide'); }); $('#cancel').click(function(){ $('.shade,.add-modal').addClass('hide'); }); }) $('#ajax_submit').click(function(){ $.ajax({ url: "/testajax", type: "POST", data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val()}, success: function(data) { # console.log(data); #获得回传数据,在console中打印出来
var obj = JSON.parse(data); #将字符串转换成为json格式 JSON.stringify():将json格式转换成为字符串
if(obj.status){ #取出json中status字段
location.reload();
}else{
$('#error_msg').text(obj.error); #取出 error字段并打印在标签‘error_msg’中
} } }) }) </script> </body> </html>
打印结果:
传递过来的json字符串,console打印出来了
使用ajax时最好使用 HttpResponse(json.dumps(data))返回一个字符串使用前端JSON.parse转换成为json格式在调用
不要使用render和redirect返回数据
案例:
$.ajax({
data: $('#edit_form').serialize(); #实现一句话提交数据,不用再写很多的对应关系
})