Ajax提交表单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="/static/common.css" rel="stylesheet"> <style> .hide { display: none; } .shadow { position:fixed; left:0; top: 0; bottom: 0; right: 0; background-color: black; opacity: 0.6; z-index: 1; } .add-app { position: fixed; height: 400px; width: 400px; margin-left:100px ; border: 1px solid indianred; top: 100px; left: 25%; background-color: white; z-index: 2; } </style> </head> <body> <h1>应用列表:</h1> <P><input type="button" value="添加" id="i1"/></P> <table border="1"> <thead> <tr> <td>应用名称</td> <td>应用主机列表</td> </tr> </thead> <tbody> {% for row in app_list%} <tr> <td>{{ row.name }}</td> <td> {% for host in row.r.all %} <span class="host_tag">{{ host.hostname }}</span> {% endfor %} </td> </tr> {%endfor%} </tbody> </table> <div class="shadow hide"></div> <form id="add_form"> <div class="add-app hide"> <input type="text" placeholder="应用名称" name="app_name"/> <div class="group"> <select id="host_list" name="host_list" multiple> {% for row in host_list %} <option value="{{row.nid}}">{{row.hostname}}</option> {% endfor %} </select> </div> <input type="submit" value="提交"> <input id="ajax_submit" type="button" value="ajax提交"> <input id='i2' type="button" value="取消"> <span id="error_msg" style="display: inline-block;color: red"></span> </div> </form> <script src="/static/jquery-3.2.1.min.js"></script> <script> $(function () { $('#i1').click(function () { $('.shadow,.add-app').removeClass('hide'); }) $('#i2').click(function () { $('.shadow,.add-app').addClass('hide'); }) $("#ajax_submit").click(function () { $.ajax({ url:'/xiaoqing/ajax_submit/', #//提交url data:$("#add_form").serialize(), # //input,select数据打包发向后台 type:'POST', # //提交请求类型 dataType:'Json', #//发送数据类型 traditional:true, #//如果是多选的话,必须加上此选项 success:function (obj) { #//发送成功后回调函数 console.log(obj); location.reload(); #刷新 location。href('http://') #跳转 }, error:function () { } }) }) }) </script> </body> </html>
def app(request): if request.method=="GET": app_list=models.Application.objects.all() host_list=models.Host.objects.all() for row in app_list: print(row.name,'-|-',row.r.all()) return render(request,'app.html',{'app_list':app_list,'host_list':host_list,}) elif request.method == "POST": appname = request.POST.get('app_name') hostlist = request.POST.getlist('host_list') print(appname,hostlist) obj = models.Application.objects.create(name=appname) obj.r.add(*hostlist) return redirect('/xiaoqing/app')