33、JS基础-ajax_post
截止目前,完成了登录,创建和删除,“编辑”这块还是老的信息。
打开
a、点击 编辑 =>(内容) => dialog
b、内容 =>
后端 ajax
页面上 遍历用户时候 button(id)
c、jQuery(selector).val(value)
d、dialog.modal('show')
编辑,提交
a、jQuery(form).serializeArray()
b、jQuery.post()
c、成功 提示sweetalert 关闭sweetalert 关闭dialog 刷新页面
d、失败 提示sweetalert
开始操作:
路由url:
path('get/ajax', views.get_ajax, name='get_ajax'),
path('update/ajax', views.update_ajax, name='update_ajax'),
视图index:
from django.core.exceptions import ObjectDoesNotExist
def get_ajax(request):
if not request.session.get('user'):
return JsonResponse({'code': 403})
uid = request.GET.get('id', '')
try:
user = User.objects.get(id=uid)
return JsonResponse({'code': 200, 'result': user.as_dict()})
except ObjectDoesNotExist as e:
return JsonResponse({'code': 400, 'errors': {'id': '用户id不存在.'}})
#####
def update_ajax(request):
if not request.session.get('user'):
return JsonResponse({'code': 403})
is_valid, user, errors = UserValidator.valid_update(request.POST)
if is_valid:
user.save()
return JsonResponse({'code': 200})
else:
return JsonResponse({'code': 400, 'errors': errors})
###
index配置
...
<td>
<a class="btn btn-success btn-xs btn-edit-user" data-id="{{ user.id }}" href="javascript:void(0)">编辑</a>
{% if request.session.user.id != user.id %}
...
<div class="modal fade" id="dialog-edit-user" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">用户编辑</h4>
</div>
<div class="modal-body">
<form class="form-horizontal form-edit-user">
{% csrf_token %}
<input type="hidden" name="id" value=""/>
<div class="form-group">
<label class="control-label col-md-3">用户名:</label>
<div class="col-md-9">
<input type="text" class="form-control" name="name" value="" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">联系方式:</label>
<div class="col-md-9">
<input type="text" class="form-control" name="tel" value="" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">年龄:</label>
<div class="col-md-9">
<input type="text" class="form-control" name="age" value="" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">性别:</label>
<div class="col-md-9">
<label class="radio-inline"><input type="radio" name="sex" value="1" checked="checked"/>男</label>
<label class="radio-inline"><input type="radio" name="sex" value="0" />女</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary btn-update-user">更新</button>
</div>
</div>
</div>
</div>
...
jQuery('#table_user').on('click', '.btn-edit-user', function () {
var id = jQuery(this).attr('data-id');
var form = jQuery('.form-edit-user');
jQuery.get("{% url 'user:get_ajax' %}", {'id':id}, function (result) {
if(result['code'] == 200){
form.find('[name=id]').val(result['result']['id']);
form.find('[name=name]').val(result['result']['name']);
form.find('[name=tel]').val(result['result']['tel']);
form.find('[name=age]').val(result['result']['age']);
//form.find('[name=sex]').val(result['result']['sex']?1:0);
if(result['result']['sex']){
form.find('[name=sex][value=1]').prop('checked', true);
}else {
form.find('[name=sex][value=0]').prop('checked', true);
}
jQuery('#dialog-edit-user').modal({
show: true,
backdrop: 'static',
keyboard: false
})
} else if (result['code'] == 400){
//alert('验证失败...');
var errors = []
jQuery.each(result['errors'], function (k,v) {
errors.push(v)
});
//alert(errors.join('\n'))
swal('验证失败', errors.join('\n'), 'error')
}else if (result['code'] == 403){
swal({
title: '未登录',
text: "未登录",
timer: 2000,
showConfirmButton: false
})
}
}, 'json');
});
jQuery('.btn-update-user').on('click', function () {
//var form = jQuery('.form-edit-user');
//console.log(form.serializeArray())
var data = jQuery('.form-edit-user').serializeArray();
jQuery.post("{% url 'user:update_ajax' %}", data, function (result) {
console.log(result);
if(result['code'] == 200){
swal({
title: "成功",
text:'',
type: "success",
closeOnConfirm: false
}, function () {
jQuery('#dialog-user-create').modal("hide");
//关闭sweetalert
swal.close();
/*刷新table*/
window.location.reload()
})
} else if (result['code'] == 400){
//alert('验证失败...');
var errors = []
jQuery.each(result['errors'], function (k,v) {
errors.push(v)
});
//alert(errors.join('\n'))
swal('验证失败', errors.join('\n'), 'error')
}else if (result['code'] == 403){
swal({
title: '未登录',
text: "未登录",
timer: 2000,
showConfirmButton: false
});
}
}, 'json');
});
</script>
页面访问演示,
弹出编辑页面,保存成功,页面验证ok,备份“cmdb09-03.rar”。
标签:jquery,jQuery,errors,form,10,--,ajax,user,result From: https://www.cnblogs.com/sunnyyangwang/p/16653870.html