码迷,mamicode.com
首页 > Web开发 > 详细

【Django】ajax

时间:2018-06-06 23:58:39      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:自动获取   加载完成   sel   ons   color   技术分享   pat   tom   spl   

1.前后端交互

技术分享图片
    <div class="shade hide"></div>               <!--遮罩层,全屏-->
    <div class="add-modal hide">                 <!--弹出框-->
        <form method="POST" action="/host/">    <!--编辑弹出框内容-->
            <div class="group">
                <input id="host" type="text" placeholder="主机名" name="hostname"/>
            </div>

            <div class="group">
                <input id="ip" type="text" placeholder="IP" name="ip"/>
            </div>

            <div class="group">
                <input id="port" type="text" 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="提交"/>
            <a id="ajax_submit" style="display: inline-block;padding:5px;background: blue;color: white">悄悄提交</a>
            <input id="cancel" type="button" value="取消"/>
        </form>
    </div>
templates/host.htmi #模版代码
技术分享图片
$(function(){
    $(#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) {
                if(data==OK){
                    location.reload()   // 重新加载页面
                }else {
                    alert(data);
                }
            }
        })
    })
})

#Ajax代码    
templates/host.html #ajax代码
技术分享图片
def test_ajax(requset):
    h = requset.POST.get(hostname)
    i = requset.POST.get(ip)
    p = requset.POST.get(port)
    b = requset.POST.get(b_id)
    if h and len(h) > 5:       #
        models.Host.objects.create(hostname=h,
                               ip=i,
                               port=p,
                               b_id=b,)
        return HttpResponse(OK)
    else:
        return HttpResponse(开不了门)
app01/views
技术分享图片
<!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 red;
            background: white;
            margin-left: -200px;
        }
    </style>
</head>
<body>
    <h1>主机列表(列表)</h1>
    <div>
        <input id="add_host" type="button" value="添加"/>    <!--模态对话框-->
    </div>
    <table border="1">

        <thead>
            <tr>
                <th>主机序号</th>
                <th>主机名字</th>
                <th>IP</th>
                <th>端口</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
                <tr aa="{{ row.nid }}" ab="{{ row.b.id }}" ac="{{ row.b.code }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.ip }}</td>
                    <td>{{ row.port }}</td>
                    <td>{{ row.b.caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <h1>主机列表(字典)</h1>
    <table border="1">
        <thead>
        <tr>
            <th>主机名字</th>
            <th>业务线名称</th>
        </tr>
        </thead>
        <tbody>
        {% for row in v2 %}
            <tr aa="{{ row.nid }}" ab="{{ row.b__id }}">
                <td>{{ row.hostname }}</td>
                <td>{{ row.b__caption }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    </table>
    <h1>主机列表(元组)</h1>
    <table border="1">
        <thead>
        <tr>
            <th>主机名字</th>
            <th>业务线名称</th>
        </tr>
        </thead>
        <tbody>
        {% for row in v3 %}
            <tr aa="{{ row.0 }}" ab="{{ row.2}}">
                <td>{{ row.1 }}</td>
                <td>{{ row.3 }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>


    <div class="shade hide"></div>               <!--遮罩层,全屏-->
    <div class="add-modal hide">                 <!--弹出框-->
        <form method="POST" action="/host/">    <!--编辑弹出框内容-->
            <div class="group">
                <input id="host" type="text" placeholder="主机名" name="hostname"/>
            </div>

            <div class="group">
                <input id="ip" type="text" placeholder="IP" name="ip"/>
            </div>

            <div class="group">
                <input id="port" type="text" 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="提交"/>
            <a id="ajax_submit" style="display: inline-block;padding:5px;background: blue;color: white">悄悄提交</a>
            <input id="cancel" type="button" value="取消"/>
        </form>
    </div>

    <script src="/static/jquery-1.12.4.js"></script>     <!--JS文件-->
    <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:"/test_ajax/",                      <!--提交到-->
                    type:POST,                              <!--什么方式提交-->
                    data:{hostname:$(#host).val(),ip:$(#ip).val(),port:$(#port).val(),b_id:$(#sel).val()},   <!--提交什么数据-->
                    success:function (data) {
                        if (data == OK){
                            location.reload()               <!--重新加载页面-->
                        }else {
                            alert(data);
                        }
                    }
                })
            })


        })
    </script>
</body>
</html>
templates/host.html总代码

2.后端发送请求,前端无法感受,且页面无反应

技术分享图片

技术分享图片
<form method="POST" action="/host/">    <!--编辑弹出框内容-->
    <div class="group">
        <input id="host" type="text" placeholder="主机名" name="hostname"/>
    </div>

    <div class="group">
        <input id="ip" type="text" placeholder="IP" name="ip"/>
    </div>

    <div class="group">
        <input id="port" type="text" 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="提交"/>
    <a id="ajax_submit" style="display: inline-block;padding:5px;background: blue;color: white">悄悄提交</a>
    <input id="cancel" type="button" value="取消"/>
    <span id="error_msg" style="color:red"></span>
</form>
templates/host.htmi #模版代码
技术分享图片
$(function () { 
    $(#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 {
                    $(#error_msg).text(obj.error);
                }
            }
        })
    })
})
templates/host.html #ajax代码
技术分享图片
def test_ajax(requset):
    import json
    ret = {status:True,error:None,data:None}
    try:
        h = requset.POST.get(hostname)
        i = requset.POST.get(ip)
        p = requset.POST.get(port)
        b = requset.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))  #字符串,形似字典
app01/views

3.serialize自动获取form表单数据

技术分享图片
<div class="edit-modal hide">                 <!--弹出框-->
    <form id="edit_form" method="POST" action="/host/">    <!--编辑弹出框内容-->
            <input type="text" name="aa" style="display: none" />
            <input id="host" type="text" placeholder="主机名" name="hostname"/>
            <input id="ip" type="text" placeholder="IP" name="ip"/>
            <input id="port" type="text" placeholder="端口" name="port"/>
            <select id="sel" name="b_id">
                {% for op in b_list %}
                <option value="{{ op.id }}">{{ op.caption }}</option>
                {% endfor %}
            </select>
        <a id="ajax_submit_edit">确认编辑</a>
    </form>
</div>
templates/host #模版代码
技术分享图片
$(function () {
    $(.edit).click(function () {
        $(.hide,.edit-modal).removeClass(hide);

        var ab = $(this).parent().parent().attr(ab);
        var aa = $(this).parent().parent().attr(aa);

        $(#edit_form).find(select).val(ab);
        $(#edit_form).find(input[name="aa"]).val(aa);

        //修改
        $.ajax({
            //data:{hostname:$(#host).val(),ip:$(#ip).val(),port:$(#port).val(),b_id:$(#sel).val()},
            data:$(#edit_form).serialize()   //取代上面一句话,通过form中的id="edit_form"值一一对应发到后台(name是name,值是值)
        })
}
templates/host.html #ajax代码
技术分享图片
<!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,.edit-modal{
            position: fixed;
            height: 300px;
            width: 400px;
            top: 100px;
            left: 50%;
            z-index: 101;
            border: 1px solid red;
            background: white;
            margin-left: -200px;
        }
    </style>
</head>
<body>
    <h1>主机列表(列表)</h1>
    <div>
        <input id="add_host" type="button" value="添加"/>    <!--模态对话框-->
    </div>
    <table border="1">

        <thead>
            <tr>
                <th>主机序号</th>
                <th>主机名字</th>
                <th>IP</th>
                <th>端口</th>
                <th>业务线名称</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
                <tr aa="{{ row.nid }}" ab="{{ row.b.id }}" ac="{{ row.b.code }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.ip }}</td>
                    <td>{{ row.port }}</td>
                    <td>{{ row.b.caption }}</td>
                    <td>
                        <a class="edit">编辑</a>|<a class="delete">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <h1>主机列表(字典)</h1>
    <table border="1">
        <thead>
        <tr>
            <th>主机名字</th>
            <th>业务线名称</th>
        </tr>
        </thead>
        <tbody>
        {% for row in v2 %}
            <tr aa="{{ row.nid }}" ab="{{ row.b__id }}">
                <td>{{ row.hostname }}</td>
                <td>{{ row.b__caption }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    </table>
    <h1>主机列表(元组)</h1>
    <table border="1">
        <thead>
        <tr>
            <th>主机名字</th>
            <th>业务线名称</th>
        </tr>
        </thead>
        <tbody>
        {% for row in v3 %}
            <tr aa="{{ row.0 }}" ab="{{ row.2}}">
                <td>{{ row.1 }}</td>
                <td>{{ row.3 }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>


    <div class="shade hide"></div>               <!--遮罩层,全屏-->
    <div class="add-modal hide">                 <!--弹出框-->
        <form method="POST" action="/host/">    <!--编辑弹出框内容-->
            <div class="group">
                <input id="host" type="text" placeholder="主机名" name="hostname"/>
            </div>

            <div class="group">
                <input id="ip" type="text" placeholder="IP" name="ip"/>
            </div>

            <div class="group">
                <input id="port" type="text" 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="提交"/>
            <a id="ajax_submit" style="display: inline-block;padding:5px;background: blue;color: white">悄悄提交</a>
            <input id="cancel" type="button" value="取消"/>
            <span id="error_msg" style="color:red"></span>
        </form>
    </div>

    <div class="edit-modal hide">                 <!--弹出框-->
        <form id="edit_form" method="POST" action="/host/">    <!--编辑弹出框内容-->
                <input type="text" name="aa" style="display: none" />
                <input id="host" type="text" placeholder="主机名" name="hostname"/>
                <input id="ip" type="text" placeholder="IP" name="ip"/>
                <input id="port" type="text" placeholder="端口" name="port"/>
                <select id="sel" name="b_id">
                    {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>
                    {% endfor %}
                </select>
            <a id="ajax_submit_edit">确认编辑</a>
        </form>


    </div>
    <script src="/static/jquery-1.12.4.js"></script>     <!--JS文件-->
    <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:"/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 {
                            $(#error_msg).text(obj.error);
                        }
                    }
                })
            })

            $(.edit).click(function () {
                $(.hide,.edit-modal).removeClass(hide);

                var ab = $(this).parent().parent().attr(ab);
                var aa = $(this).parent().parent().attr(aa);

                $(#edit_form).find(select).val(ab);
                $(#edit_form).find(input[name="aa"]).val(aa);

                //修改
                $.ajax({
                    //data:{hostname:$(#host).val(),ip:$(#ip).val(),port:$(#port).val(),b_id:$(#sel).val()},
                    data:$(#edit_form).serialize()   //取代上面一句话,通过form中的id="edit_form"值一一对应发到后台(name是name,值是值)
                })
                //更新
                //models.host.objects.filter(nid=nid).update()
            })
        })
    </script>
</body>
</html>
templates/host.html #总代码

技术分享图片

4.多对多表单操作

技术分享图片
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64,db_index=True)
    ip = models.GenericIPAddressField(protocol=ipv4,db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to=Business,to_field=id)

#创建多对多
# 方法一:(自定义关系表)
# class HosttoApp(models.Model):
#     hobj = models.ForeignKey(to="Host",to_field=‘nid‘)
#     aobj = models.ForeignKey(to="App",to_field="id")

class App(models.Model):
    name = models.CharField(max_length=32)
    # 方法二:(自动创建关系表)
    r = models.ManyToManyField("Host")
app01/models(方法二创建)
技术分享图片
def app(request):

    app_list = models.App.objects.all()
    for row in app_list:
        print(row.name,row.r.all())

    return render(request,app.html,{app_list:app_list})
app01/views
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .host_tag{
            display:inline-block ;
            padding: 3px;
            border: 2px solid blue;
            background-color: red;
        }
    </style>
</head>
<body>

    <h1>应用列表</h1>

    <table border="1">
        <thead>
            <tr>
                <td>应用名称</td>
                <td>应用主机列表</td>
            </tr>
        </thead>
        <tbody>
            {% for app in app_list %}
            <tr>
                <td>{{ app.name }}</td>
                <td>
                    {% for abc in app.r.all %}
                        <span class="host_tag">{{ abc.hostname }}</span>
                        {% endfor %}
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>
templates/app.html

技术分享图片

4.1 多对多 app.html通过form刷新增加表单数据

技术分享图片
<div class="shade hide"></div>               <!--遮罩层,全屏-->
<div class="add-modal hide">                 <!--弹出框-->
    <form id="add_form" method="POST" action="/app/">    <!--编辑弹出框内容-->
        <div class="group">
            <input id="app_name" type="text" placeholder="应用名称" name="app_name"/>
        </div>

        <div class="group">
            <select id="host_list" name="host_list" multiple>
                {% for op in host_list %}
                    <option value="{{ op.nid }}">{{ op.hostname }}</option>
                {% endfor %}
            </select>
        </div>

        <input type="submit" value="提交"/>

    </form>
</div>
templates/app.html
技术分享图片
def app(request):
    if request.method == GET:
        app_list = models.App.objects.all()
        # for row in app_list:
        #     print(row.name,row.r.all())

        host_list = models.Host.objects.all()
        return render(request,app.html,{app_list:app_list,host_list:host_list})
    elif request.method == POST:
        app_name = request.POST.get(app_name)
        host_list = request.POST.getlist(host_list)
        print(app_name,host_list)

       #增加
        obj = models.App.objects.create(name=app_name)
        obj.r.add(*host_list)

        return redirect(/app/)
app01/views

技术分享图片

4.2 多对多 app.html通过ajax增加表单数据(dataType,traditional)

技术分享图片
<script>
    $(function () {                                     <!--页面框架加载完成-->

        $(#add_app).click(function () {              <!--绑定事件-->
            $(.shade,.add-modal).removeClass(hide); <!--点击添加按钮,呼出遮罩层与弹出框-->
        });

        $(#cancel).click(function () {
            $(.shade,.add-modal).addClass(hide);
        });
        
        $(#add_submit_ajax).click(function () {
            $.ajax({
                url:/ajax_app/,
                //data:{user:123,host_list:[1,2,3,4]},
                data:$(#add_form).serialize(),
                type:"POST",
                dataType:JSON,    //预期服务器返回的数据类型,代替了obj = JSON.parse(data);
                traditional:true,   //告诉jquery,此处除了字符串,有其他模式(如:list列表)
                success:function (data) {
                    //console.log(data);
                    location.reload();
                },
                error:function () {
                    
                }
            })
        })

    })
    
</script>
templates/app.html #Ajax代码
技术分享图片
def ajax_app(request):
    ret = {status:True,error:None,data:None}
    # print(request.POST.get(‘user‘))
    # print(request.POST.getlist(‘host_list‘))
    app_name = request.POST.get(app_name)
    host_list = request.POST.getlist(host_list)
    data = models.App.objects.create(name=app_name)
    data.r.add(*host_list)
    return HttpResponse(json.dumps(ret))
app01/views
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .host_tag{
            display:inline-block ;
            padding: 3px;
            border: 2px solid blue;
            background-color: red;
        }
        .hide{
            display: none;
        }
        .shade{
            position: fixed;
            top: 0;
            right:0 ;
            left: 0;
            bottom: 0;
            background: black;
            opacity: 0.6;
            z-index: 100;
        }
        .add-modal,.edit-modal{
            position: fixed;
            height: 300px;
            width: 400px;
            top: 100px;
            left: 50%;
            z-index: 101;
            border: 1px solid red;
            background: white;
            margin-left: -200px;
        }
    </style>
</head>
<body>

    <h1>应用列表</h1>
    <div>
        <input id="add_app" type="button" value="添加"/>    <!--模态对话框-->
    </div>
    <table border="1">
        <thead>
            <tr>
                <td>应用名称</td>
                <td>应用主机列表</td>
            </tr>
        </thead>
        <tbody>
            {% for app in app_list %}
            <tr>
                <td>{{ app.name }}</td>
                <td>
                    {% for abc in app.r.all %}
                        <span class="host_tag">{{ abc.hostname }}</span>
                        {% endfor %}
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <div class="shade hide"></div>               <!--遮罩层,全屏-->
    <div class="add-modal hide">                 <!--弹出框-->
        <form id="add_form" method="POST" action="/app/">    <!--编辑弹出框内容-->
            <div class="group">
                <input id="app_name" type="text" placeholder="应用名称" name="app_name"/>
            </div>

            <div class="group">
                <select id="host_list" name="host_list" multiple>
                    {% for op in host_list %}
                        <option value="{{ op.nid }}">{{ op.hostname }}</option>
                    {% endfor %}
                </select>
            </div>

            <input type="submit" value="提交"/>
            <input id="add_submit_ajax" type="button" value="Ajax提交"/>
        </form>
    </div>


    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {                                     <!--页面框架加载完成-->

            $(#add_app).click(function () {              <!--绑定事件-->
                $(.shade,.add-modal).removeClass(hide); <!--点击添加按钮,呼出遮罩层与弹出框-->
            });

            $(#cancel).click(function () {
                $(.shade,.add-modal).addClass(hide);
            });
            
            $(#add_submit_ajax).click(function () {
                $.ajax({
                    url:/ajax_app/,
                    //data:{user:123,host_list:[1,2,3,4]},
                    data:$(#add_form).serialize(),
                    type:"POST",
                    dataType:JSON,    //预期服务器返回的数据类型,代替了obj = JSON.parse(data);
                    traditional:true,   //告诉jquery,此处除了字符串,有其他模式(如:list列表)
                    success:function (data) {
                        //console.log(data);
                        location.reload();
                    },
                    error:function () {
                        
                    }
                })
            })

        })

    </script>
</body>
</html>
templates/app.html #总代码(供参考)
技术分享图片
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
import json
# Create your views here.

def business(requset):
    v1 = models.Business.objects.all()
    #QuerySet
    #[obj(id,caption,code),obj(id,caption,code),obj(id,caption,code)]

    v2 = models.Business.objects.all().values(id,caption)
    # QuerySet
    # [{‘id‘:1,‘caption‘:‘苹果‘},{‘id‘:2,‘caption‘:‘‘香蕉},{‘id‘:3,‘caption‘:‘菠萝‘},{‘id‘:4,‘caption‘:‘梨子‘}]

    v3 = models.Business.objects.all().values_list(id,caption)
    # QuerySet
    # [(0,苹果),(2,香蕉)]
    return render(requset,business.html,{v1:v1,v2:v2,v3:v3})


# def host(request):
#     v1 = models.Host.objects.filter(nid__gt=0)
#     for row in v1:
#         print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.id,row.b.caption,row.b.code,sep=‘\t‘)
#
#     v2 = models.Host.objects.filter(nid__gt=0).values(‘nid‘,‘hostname‘,‘b_id‘,‘b__caption‘)
#     # print(v2)
#     for row in v2:
#         print(row[‘nid‘],row[‘hostname‘],row[‘b_id‘],row[‘b__caption‘])
#
#     v3 = models.Host.objects.filter(nid__gt=0).values_list(‘nid‘,‘hostname‘,‘b_id‘,‘b__caption‘)
#     # #print(v3)
#     for row in v3:
#          print(row)
#
#     # return HttpResponse(‘戴利祥‘)
#     return render(request,‘host.html‘,{‘v1‘: v1, ‘v2‘:v2 ,‘v3‘:v3})


def host(request):
    if request.method == GET:
        v1 = models.Host.objects.filter(nid__gt=0)
        v2 = models.Host.objects.filter(nid__gt=0).values(nid,hostname,b_id,b__caption)
        v3 = models.Host.objects.filter(nid__gt=0).values_list(nid,hostname,b_id,b__caption)

        b_list= models.Business.objects.all()

        return render(request,host.html,{v1: v1, v2:v2 , v3:v3 ,b_list:b_list})

    elif request.method == POST:
        h = request.POST.get(hostname)
        i = request.POST.get(ip)
        p = request.POST.get(port)
        b = request.POST.get(b_id)
        # models.Host.objects.create(hostname=h,
        #                            ip=i,
        #                            port=p,
        #                            b=models.Business.objects.get(id=b)
        #                            )
        models.Host.objects.create(hostname=h,
                                   ip=i,
                                   port=p,
                                   b_id=b,
                                    )
        return redirect(/host)   #以get分方式重新访问http://127.0.0.1:8000/host/


def test_ajax(requset):
    import json
    ret = {status:True,error:None,data:None}
    try:
        h = requset.POST.get(hostname)
        i = requset.POST.get(ip)
        p = requset.POST.get(port)
        b = requset.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))  #字符串,形似字典

def app(request):
    if request.method == GET:
        app_list = models.App.objects.all()
        # for row in app_list:
        #     print(row.name,row.r.all())

        host_list = models.Host.objects.all()
        return render(request,app.html,{app_list:app_list,host_list:host_list})
    elif request.method == POST:
        app_name = request.POST.get(app_name)
        host_list = request.POST.getlist(host_list)
        print(app_name,host_list)

       #增加
        obj = models.App.objects.create(name=app_name)
        obj.r.add(*host_list)

        return redirect(/app/)

def ajax_app(request):
    ret = {status:True,error:None,data:None}
    # print(request.POST.get(‘user‘))
    # print(request.POST.getlist(‘host_list‘))
    app_name = request.POST.get(app_name)
    host_list = request.POST.getlist(host_list)
    data = models.App.objects.create(name=app_name)
    data.r.add(*host_list)
    return HttpResponse(json.dumps(ret))
app01/views #总代码(供参考)
技术分享图片
from django.contrib import admin
from django.conf.urls import url
from app01 import views
# from django.urls import path

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^business/, views.business),
    url(r^host/, views.host),
    url(r^test_ajax/, views.test_ajax),
    url(r^app/, views.app),
    url(r^ajax_app/, views.ajax_app),
]
day2/urls.py #总代吗(供参考)

技术分享图片

 

【Django】ajax

标签:自动获取   加载完成   sel   ons   color   技术分享   pat   tom   spl   

原文地址:https://www.cnblogs.com/dalyday/p/8910471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!