前言
实现前后端分离,异步刷新
1.应用文件中配置路由urls.py
urlpatterns = [
url(r'sajax/', views.sajax),
]
urlpatterns += router.urls
2.配置views.py
def sajax(request):
if request.method == 'GET':
return render(request, 'stuajax.html')
3.配置html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>展示所有学生</title>
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript">
<scipt>
{#第一种写法#}
$(function () {
$('#showStus').click(function () {
$.get('/stu/student/', function (msg) {
s = '<table><tr><td>ID</td><td>姓名</td><td>电话</td></tr><td>操作</td></tr>'
for ( var i=0; i<msg.data.length; i++) {
s += '<tr><td>' + msg.data[i].id + '</td>' +
'<td>' + msg.data[i].s_name + '</td>' +
'<td>' + msg.data[i].s_tel + '</td>' +
'<td>'+ '<a href="javascript:;" onclick="update_stu(' + msg.data[i].id +')" >编辑</a></td>' +
'<td>' +'<a href="javascript:;" onclick="del_stu(' + msg.data[i].id+ ')">删除</a></td></tr>'
}
s += '</table>'
$('#div_stus').html(s)
}, 'json');
});
});
{#第二种json写法#}
{#改变状态#}
function cartchangeselect(cart_id){
csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
url:'/stu/change/',
type:'POST',
data:{'cart_id':cart_id},
dataType:'json',
headers:{'X-CSRFToken':csrf},
success:function(msg){
if(msg.is_select){
// 偷天换日
s = '<span id="selectallgoodsid" onclick="cartchangeselect(' + cart_id +')">√</span>'
}else{
s = '<span id="selectallgoodsid" onclick="cartchangeselect(' + cart_id +')">X</span>'
}
$('#changeselect_' + cart_id).html(s)
},
error:function(msg){
alert('请求失败')
}
});
};
</script>
</head>
<body>
<input id="showStus" type="button" value="获取">
{# <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>#}
<div id="div_stus">
</div>
<div id="div_update_stus"></div>
<input onclick="createStu()" type="button" value="创建">
<div id="div_create_stu"></div>
{% csrf_token %}
</body>
</html>
4.views.py中处理请求, 返回数据
def user_change_select(request):
if request.method == 'POST':
cart_id = request.POST.get('cart_id')
user = request.user
data = {
'code': '200',
'msg': '请求成功'
}
if user and user.id:
cart = CartModel.objects.filter(pk=cart_id).first()
if cart.is_select:
cart.is_select = False
else:
cart.is_select = True
cart.save()
data['is_select'] = cart.is_select
return JsonResponse(data)
网友评论