16)django-ajax使用

通过ajax可以悄悄的把数据传输给服务器,实现页面无刷新。

一:ajax使用语法

  1)普通方式

    ajax使用语法:
    $.ajax({
        url:"/host", //提交到那里
        type:"POST", //提交类型
        data:{"k1":"v1","k2":"v2"} //提交的数据
        success:function(data1){ //success不会直接运行,当服务器有数据传输过来才会触发执行。
                    匿名函数必须要有一个参数,用来接受数据,data1用来接受是服务器端返回字符串数据 alter(data1); } })

  示例:

#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({
            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']}>
View Code
    #示例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()
            })
View Code

 3)如果页面的数据是列表,上面的数据传输到后台处理不了

 
    #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与非 ajax多对多数据

  

    #增加数据例子(非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;
                     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);
                }
        )

    
View Code
原文地址:https://www.cnblogs.com/lixiang1013/p/7784470.html