AJAX刷新
特点: 异步提交,局部刷新
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>32期皇家会所会员ajax登录页面</h1>
用户名: <input type="text" id="username">
密码: <input type="password" id="password">
<button id="btn">ajax提交</button>
<h1 id="ajax_error" style="color:Red;"></h1>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// 形参是自命名的
$('#btn').click(function (){
var uname = $("#username").val();
var password = $("#password").val();
$.ajax({
type:'post', // 请求方法.
url:'/login/',
data:{xname:uname, pwd:password}, // xname:chao,pwd:123 request.POST.get('xname')
success:function (res){ // res接受的是请求成功之后的响应结果,如果ajax判断请求成功和失败,有后台决定
// 后台响应的状态码如果是2xx\3xx等,ajax发现应用状态为2xx\3xx等,ajax就知道请求成功了
// ajax会自动触发success对应的回调函数,并且将接受到的响应传值给了函数
console.log('success',res);
},
error:function (error){ //后台响应的状态码为4xx或者5xx表示请求失败或者服务器出问题了,没有正常响应本次请求的内容
console.log('error>>>>>',error); // ajax接受到响应,如果发现响应状态码为4xx或者5xx,那么ajax会自动触发error对应的函数,并将
// 响应结果传给函数作为参数(error参数)
{#$('#ajax_error').text('输入的用户名或者密码有误!');#}
$('#ajax_error').text(error.responseText); // 提取后端返回的值
}
})
})
</script>
</html>
后端代码
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
data = request.POST
print(data) #<QueryDict: {'xname': ['yuantao'], 'pwd': ['666']}>
username = data.get('xname')
password = data.get('pwd')
if username == 'yuantao' and password == '666':
return HttpResponse('ok') # 200
# ret = render(request, 'login.html', {'error':'用户名或者密码有误!!', 'username':username,'password':password}) 默认返回200 需修改ST码
ret = HttpResponse('not ok')
ret.status_code = 400 # 修改返回的ST码 规格化开发
return ret
AJAX获得数据
后端代码
def index(request):
userinfo = {
'name':'春培',
'age': 18,
}
return JsonResponse(userinfo) # 自动完成序列化 反序列化
前端代码
$.ajax({
url:'/index/',
type:'get',
success:function (res){
// 可以直接使用 res.name 提取 js数组对象
},
});
AJAX实例
前端代码
{% extends 'base.html' %}
{% block content_title %}
<h1>查看书籍</h1>
{% endblock %}
{% block content %}
<a href="{% url 'add_book' %}" class="btn btn-primary">添加书籍</a>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>编号</th>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期</th>
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in book_objs %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publishDate|date:'Y-m-d' }}</td>
<td>{{ book.publishs.name }}</td>
<td>{{ book.get_authors_name }}</td>
<td>
<a href="{% url 'edit_book' book.id %}" class="btn btn-warning">编辑</a>
<a href="{% url 'del_book' book_id=book.id %}" class="btn btn-danger">删除</a>
<button class="btn btn-danger ajax_sub" xx="{{ book.pk }}">ajax删除</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block js %}
<script>
$(".ajax_sub").click(function () {
var book_id = $(this).attr('xx'); //获取xx属性对应的值
var ths = $(this); // 保存一下这个this 因为再调用是 isConfirm 的指针了
swal({
title: "are you sure?",
text: "开弓没有回头箭!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "确认删除",
cancelButtonText: "容我三思",
closeOnConfirm: false
}, function (isConfirm) {
$.ajax({
type:'get',
url:'/ajax_del_book/' + `${book_id}` + '/', // http://127.0.0.1:8000/ajax_del_book/1/
success:function (res){
if (res.status === 1){
swal("删除成功!", "该条记录已被删除", "success");
ths.parent().parent().remove();
}else {
swal("删除失败", "删除动作有有误!", "error");
}
},
})
})
});
</script>
{% endblock %}
后端代码
def ajax_del_book(request,book_id):
try:
models.Book.objects.get(id=book_id).delete() # 默认级联删除
res_data = {'status': 1, 'msg': '删除成功!'}
except:
res_data = {'status': 0, 'msg': '删除失败!'}
return JsonResponse(res_data)
url:'/ajax_del_book/' + `${book_id}` + '/', # // http://127.0.0.1:8000/ajax_del_book/1/
# 如果 不是/ 开头 会自动在当前url后继续增加 否则拼接套接字
book.pk # 获得id值
标签:res,request,ajax,AJAX,book,error,data
From: https://www.cnblogs.com/wbcde116/p/18183185