1. 程式人生 > >Django框架學習筆記(16.利用ajax實現簡易的驗證)

Django框架學習筆記(16.利用ajax實現簡易的驗證)

繼續上一篇的例子:

host.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
.hide {
            display: none;
}

        .shade {
            position: fixed;
top: 0;
right: 0;
bottom
: 0; left: 0; background-color: black; opacity: 0.6; z-index: 100; } .add-model { position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid red; background-color: 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 hid="{{ row.nid }}" bid="{{ row.b_id }}"> <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><div class="shade hide"></div> <div class="add-model 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> <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-color: green; color: white">ajax提交</a> <input id="cancel" type="button" value="取消"/> </form> </div> <script src="/static/jquery1.js"></script> <script> $(function () { $('#add_host').click(function () { $('.shade,.add-model').removeClass('hide') }); $('#cancel').click(function () { $('.shade,.add-model').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>

views.py中加入:

def test_ajax(request):
    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)
        return HttpResponse("OK")
    else:
        return HttpResponse("主機名太短")

urls.py中加入:

url(r'test_ajax$', views.test_ajax),

執行:

如果輸入的少於5,就會彈出這樣的對話方塊,如果正常,就會重新整理頁面。並且加入了新新增的資料


這裡還有不完善的地方,可以繼續修改下:

views.py:

def test_ajax(request):
    import json
    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))

host.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
.hide {
            display: none;
}

        .shade {
            position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: black;
opacity: 0.6;
z-index: 100;
}

        .add-model {
            position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background-color: 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 hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <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><div class="shade hide"></div>
<div class="add-model 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>
            <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-color: green; color: white">ajax提交</a>
        <input id="cancel" type="button" value="取消"/>
        <span id="error_msg" style="color: red"></span>
    </form>
</div>
<script src="/static/jquery1.js"></script>
<script>
$(function () {
        $('#add_host').click(function () {
            $('.shade,.add-model').removeClass('hide')
        });
$('#cancel').click(function () {
            $('.shade,.add-model').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);
}
                }
            })

        })
    })
</script>
</body>
</html>

效果就是這樣:



還可以設定編輯和取消:

這裡簡單地寫下思路:

host.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
.hide {
            display: none;
}

        .shade {
            position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: black;
opacity: 0.6;
z-index: 100;
}

        .add-model, .edit-model {
            position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background-color: 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 hid="{{ row.nid }}" bid="{{ row.b_id }}">
            <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><div class="shade hide"></div>
<div class="add-model 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>
            <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-color: green; color: white">ajax提交</a>
        <input id="cancel" type="button" value="取消"/>
        <span id="error_msg" style="color: red"></span>
    </form>
</div>
<div class="edit-model hide">
    <form id="edit_form" method="POST" action="/host">
        <input type="text" name="nid" style="display: none"/>
        <input type="text" placeholder="主機名" name="hostname"/>
        <input type="text" placeholder="IP" name="ip"/>
        <input type="text" placeholder="埠" name="port"/>
        <select 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/jquery1.js"></script>
<script>
$(function () {
        $('#add_host').click(function () {
            $('.shade,.add-model').removeClass('hide')
        });
$('#cancel').click(function () {
            $('.shade,.add-model').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 () {
            $('.shade,.edit-model').removeClass('hide');
var bid = $(this).parent().parent().attr('bid');
var nid = $(this).parent().parent().attr('hid');
$('#edit_form').find('select').val(bid);
$('#edit_form').find('input[name="nid"]').val(nid);
$.ajax({
                data: $('#edit_form').serialize()
            });
//models.Host.objects.filter(nid=nid).update()即可
})
    })
</script>
</body>
</html>