背景:
基于Django项目的Ajax向后端提交数据,向后端提交数据可以采用form表单的形式提交,但是form表单提交之后页面会刷新,如果是提交少量数据通常使用模态框的形式进行提交,而刷新页面会导致html页面重新加载,从而退出模态框,要实现在校验提交的数据不合法的场景下,需要保留模态框页面提示错误重新输入和重新提交,因此采用ajax向后端提交即可实现需求
后端页面处理函数:
# 班级展示函数
def class_list(request):
conn = pymysql.connect(host='192.168.1.124',port=3306,user='user1',password='123456',database='studentdb',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "select id,name from classes"
cursor.execute(sql)
ret_lst = cursor.fetchall()
cursor.close()
conn.close()
print(ret_lst)
return render(request,'class_lst.html',{'class_lst':ret_lst})
# 添加班级函数
def add_class(request):
name = request.POST.get('name')
if name:
conn = pymysql.connect(host='192.168.1.124',port=3306,user='user1',password='123456',database='studentdb',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "insert into classes(name) value(%s)"
cursor.execute(sql,name)
conn.commit()
cursor.close()
conn.close()
return HttpResponse('1')
else:
return HttpResponse("班级名不能为空")
前端页面简单框架:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>班级展示页</title>
<style>
.hide {
display: none;
}
.bk {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
z-index: 998;
}
.model {
position: fixed;
left: 50%;
top: 50%;
width: 400px;
height: 300px;
margin-left: -200px;
margin-top: -150px;
background-color: white;
z-index: 999;
}
</style>
</head>
<body>
{#给添加按钮绑定点击事件,发生点击则执行ShowModel函数#}
<input type="button" value="添加" onclick="ShowModel();"/>
<div id="b" class="bk hide"></div>
<div id="m" class="model hide">
<label>请输入用户名:
<input class="username" type="text" name="name" /><span class="error" style="color: red"></span>
</label>
{# 给提交按钮绑定点击事件,发生点击则执行AjaxSend函数#}
<input type="button" value="提交" onclick="AjaxSend();"/>
</div>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>班级名</th>
</tr>
</thead>
<tbody>
{% for row in class_lst %}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
function ShowModel() {
{#DOM操作移除模态框的隐藏类#}
document.getElementById('b').classList.remove('hide');
document.getElementById('m').classList.remove('hide');
}
function AjaxSend() {
$.ajax({
{#指定数据发送的目的url#}
url:'/edit_class/',
{#指定提交数据的方式#}
type:'POST',
{#要发送的数据#}
data:{'name':$(".username").val()},
success:function (ret) {
//当服务端处理完成后自动调用此函数,ret是服务端返回的值
if(ret === '1'){
{#console.log('ok');#}
{#location.href 跳转到指定页面#}
location.href = '/class_list/';
}else {
$(".error").text(ret);
}
}
})
}
</script>
</body>
</html>