經過ajax能夠悄悄的把數據傳輸給服務器,實現頁面無刷新。html
1)普通方式前端
ajax使用語法: $.ajax({ url:"/host", //提交到那裏 type:"POST", //提交類型 data:{"k1":"v1","k2":"v2"} //提交的數據 success:function(data1){ //success不會直接運行,當服務器有數據傳輸過來纔會觸發執行。
匿名函數必需要有一個參數,用來接受數據,data1用來接受是服務器端返回字符串數據 alter(data1); } })
示例:jquery
#ajax使用例子1 urls.py url(r'^test_ajax$', views.ajax_submit), views.py def ajax_submit(request): if request.method=="POST": print(request.POST.get("k1"),request.POST.get("k2")) return HttpResponse("home") 模板: <a id="ajax_submit">悄悄的提交</a> script: $("#ajax_submit").click(function() { $.ajax({ url: "/test_ajax", type: "POST", data: {"k1": "v1", "k2": "v2"}, success: function (data1) { alert(data1); } }) })
2)經過頁面傳遞數據 ajax
$.ajax({ url: "/test_ajax", type: "POST", data: {"hostname":$("#hostname").val(),"ip":$("#ip").val(),"port":$("#port").val(),"group_id":$("#group_id").val()}, success: function (data1) { alert(data1); } })
data: {"hostname":$("#hostname").val(),"ip":$("#ip").val(),"port":$("#port").val(),"group_id":$("#group_id").val()},
能夠經過以下方式代替:
data: $('#add_form').serialize(),把放有form表單數據都打包到後臺,不須要本身一個個寫字典數據
$.ajax({ url: "/test_ajax", type: "POST", data:$("#add_form").serialize(), success: function (data1) { alert(data1); } })
#ajax使用例子2 傳遞頁面數據給後臺 <form action="/host" method="post"> <div class="group"> <input type="text" name="hostname" id="hostname" placeholder="請輸入主機名"> </div> <div class="group"> <input type="text" name="ip" id="ip" placeholder="請輸入主機IP"> </div> <div class="group"> <input type="text" name="port" id="port" placeholder="請輸入主機端口"> </div> <div class="group"> <select name="group_id" id="group_id"> {% for group in v4 %} <option value="{{ group.id }}">{{ group.caption }}</option> {% endfor %} </select> </div> <div class="group"> <input type="submit" value="提交"> <input type="button" value="取消"> <a id="ajax_submit" style="cursor: pointer">悄悄的提交</a> </div> </form> $("#ajax_submit").click(function() { $.ajax({ url: "/test_ajax", type: "POST", data: {"hostname":$("#hostname").val(),"ip":$("#ip").val(),"port":$("#port").val(),"group_id":$("#group_id").val()}, success: function (data1) { alert(data1); } }) }) def ajax_submit(request): if request.method=="POST": print(request.POST) return HttpResponse("home") 輸出結果:<QueryDict: {'hostname': ['22'], 'ip': ['11'], 'group_id': ['1']}>
#示例3--返回驗證數據:爲何要加try,若是後臺要異常了,前端頁面是不能感知的,因此咱們加try拋出異常,並給前端提交ret def test_ajax(request): ret = {'status': True, 'error': None, 'data': None} 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)) $('#ajax_submit').click(function(){ $.ajax({ url: "/test_ajax", type: 'POST', data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val()}, success: function(data){ var obj = JSON.parse(data);//字符串轉對象 if(obj.status){ location.reload(); //若是沒有錯從新加載頁面(刷新)) }else{ $('#erro_msg').text(obj.error); } } }) }); ## data: $('#add_form').serialize(),把放有form表單數據都打包到後臺,不須要本身一個個寫字典數據 data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val()}, <===> data:$("#add_form").serialize(), 表格中的數據,有id可是在點編輯的時候就會沒有,因此要把id傳遞給編輯 在編輯對話框裏傳遞<input type="text" name="nid" style="display:none"> $('.edit').click(function(){ $('.shade,.edit-modal').removeClass('hide'); var bid = $(this).parent().parent().attr('bid'); var nid = $(this).parent().parent().attr('hid'); 傳遞nid $('#edit_form').find('select').val(bid); //設置下拉框默認值 $('#edit_form').find('input[name="nid"]').val(nid);//設置傳遞的nid // 修改 /* $.ajax({ data: $('#edit_form').serialize() }); */ // models.Host.objects.filter(nid=nid).update() })
3)若是頁面的數據是列表,上面的數據傳輸到後臺處理不了json
#ajax添加,注意列表 $("#ajax_buttom").click( function(){ $.ajax( { url:"/ajax_add_app", type:"POST", dataType:'JSON',//==>JSON.parse(data) data:{"k1":[1,2,3,4]},//data:{"k1":[1,2,3]}傳入後臺會處理不了.發列表須要加參數 traditional:true traditional:true, success:function(data){ alert(data); }, error:function(data){ //執行失敗執行 }} ) } )
#增長數據例子(非ajax) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .shade { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-color: #333333; opacity: 0.6; z-index: 9; } .add-mode { position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; margin-left: -200px; z-index: 11; background-color: white; } .hide { display: none; } </style> </head> <body> <input type="button" value="增長" id="add_host"> <h1>應用列表</h1> <table border="1px"> <thead> <tr> <td>應用名稱</td> <td>應用主機列表</td> </tr> </thead> <tbody> {% for app in app_list %} <tr> <td>{{ app.name }}</td> <td>{% for r in app.r.all %} <span>{{ r.hostname }}</span> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> <div class="shade hide"></div> <div class="add-mode hide"> <form action="{% url "app" %}" id="add_form" method="post"> <div class="group"> <input type="text" name="app_name" id="app_name" placeholder="請輸入應用名"> </div> <div class="group"> <select name="host_list" id="host_list" multiple="multiple"> {% for host in host_list %} <option value="{{ host.nid }}">{{ host.hostname }}</option> {% endfor %} </select> </div> <div class="group"> <input type="submit" value="提交" id="add_ok"> <input type="button" value="取消"> </div> </form> </div> <script src="/static/jquery-1.12.4.js"></script> <script> $("#add_host").click( function () { $(".shade,.add-mode").removeClass("hide") console.log($(".shade,.add-mode")) } ) </script> </body> </html> --------------------- def app(request): if request.method=="GET": app_list=Application.objects.all() # for app_tmp in app_list: # print(app_tmp.name,app_tmp.r.all()) host_list=Host.objects.all() return render(request,"app.html",{"app_list":app_list,"host_list":host_list}) elif request.method=="POST": #先建立application app_name=request.POST.get("app_name") host_list=request.POST.getlist("host_list")#列表 obj=Application.objects.create(name=app_name)#create會返回當前建立的對象 obj.r.add(*host_list) return redirect("/app") #ajax添加,注意列表 $("#ajax_buttom").click( function(){ $.ajax( { url:"/ajax_add_app", type:"POST", dataType:'JSON',//==>JSON.parse(data) data:{"k1":[1,2,3,4]},//data:{"k1":[1,2,3]}傳入後臺會處理不了.發列表須要加參數 traditional:true traditional:true, success:function(data){ alert(data); }, error:function(data){ //執行失敗執行 } } ) } ) def ajax_add_app(request): if request.method=="POST": list_1=request.POST.getlist("k1") print(list_1) return HttpResponse("OK") -------------- [02/Nov/2017 15:40:04] "POST /ajax_add_app HTTP/1.1" 200 2 ['1', '2', '3', '4'] #刪除,編輯 編輯 <div class="edit-mode hide"> <form action="{% url "app" %}" id="add_form" method="post"> <div class="group"> <input type="text" name="app_name" id="app_name" placeholder="請輸入應用名"> </div> <div class="group"> <select name="host_list" id="host_list" multiple="multiple"> {% for host in host_list %} <option value="{{ host.nid }}">{{ host.hostname }}</option> {% endfor %} </select> </div> <div class="group"> <input type="submit" value="提交" id="add_ok"> <input type="button" value="ajax提交" id="ajax_buttom"> </div> </form> </div> $(".edit_a").click( function(){ $(".shade,.edit-mode").removeClass("hide"); //把獲取的數據加入列表 var host_list=[] $(this).parent().prev().children().each( function(){ host_list.push($(this).attr("hid")) } ) $(".edit-mode").find("select").val(host_list); } )