Django - Ajax初识

当需要在弹出的对话框中,做判断操作时,需要用到ajax

1、host.html

  

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.shade{
top:0;
left:0;
right:0;
bottom:0;
background:black;
z-index: 100;
position: fixed;
opacity: 0.3;
}
.add-modle{
position: fixed;
height: 300px;
width: 400px;
top:100px;
left: 50%;
z-index: 101;
background: white;
margin-left: -200px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<h1>主机列表</h1>
<div>
<input id="add_host" type="text" value="添加">
</div>

<table border="1">
<thead>
<tr>
<th>主机ID</th>
<th>主机名</th>
<th>主机IP</th>
<th>主机Port</th>
<th>业务线</th>
</tr>
</thead>
<tbody>

{% for row in v %}
<tr host-id="{{ row.nid }}" cap-id="{{ 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>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>主机IP</th>
<th>主机Port</th>
<th>业务线</th>
</tr>
</thead>
<tbody>

{% for row in v2 %}
<tr host-id="{{ row.nid }}" cap-id="{{ row.b.id }}">
<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>
<form method="post" action="/app01/host">
<div class="add-modle hide">
<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="select" name="b_id">
{% for rp in b_list %}
<option value="{{ rp.id }}">{{ rp.caption }}</option>
{% endfor %}

</select>
</div>
<div class="group">
<input type="submit" value="提交" >
<a id="ajax_sub" style="display: inline-block;padding: 5px;background: blue;color: white">默默提交</a>
<input type="button" value="取消">
</div>
</div>
</form>
<script src="/static/jquery.min.js"></script>
<script>
$(function () {
$("#add_host").click(function () {
$(".shade,.add-modle").removeClass("hide")
});
$("#ajax_sub").click(function () {
$.ajax({
url:'/app01/ajax_text',
type:"POST",
data:{
'hostname':$('#host').val(),
'ip':$("#ip").val(),
'port':$("#port").val(),
"b_id":$("#select").val()

},
success:function (data) {
if (data=="ok"){
location.reload()
}
else {
alert(data)
}

}
})
})

})


</script>
</body>
</html>

2、在urls.py中,增加url和函数对应关系
  

3、在views.py中,增加函数获取前端值及写入数据库

  

猜你喜欢

转载自www.cnblogs.com/wulafuer/p/9378151.html