ajaxtony 2020-01-10
class Book(models.Model):
title = models.CharField(max_length=32)
authors = models.ManyToManyField(to=‘Author‘)
# orm就会自动帮你创建第三张表
class Author(models.Model):
name = models.CharField(max_length=32)class Book(models.Model):
title = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
book = models.ForeignKey(to=‘Book‘)
author = models.ForeignKey(to=‘Author‘)
create_time = models.DateField(auto_now_add=True)class Book(models.Model):
title = models.CharField(max_length=32)
authors = models.ManyToManyField(to=‘Author‘,through=‘Book2Author‘,through_fields=(‘book‘,‘author‘))
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField(to=‘Author‘,through=‘Book2Author‘,through_fields=(‘author‘,‘book‘))
class Book2Author(models.Model):
book = models.ForeignKey(to=‘Book‘)
author = models.ForeignKey(to=‘Author‘)
create_time = models.DateField(auto_now_add=True)三种方式的特点:
全自动:
- 好处:第三张表自动创建,orm查询方便
- 不足:无法扩展额外的字段
纯手写:
- 好处:可以扩展额外的字段
- 不足:orm查询时候会带来不便,没有正反向查询
半自动:
- 好处:既可以扩展额外字段,又方便orm查询
- 不足:无法利用add、set、remove、clear(解决:自己手动操作第三张表)
Ajax不是一门新的语言,其实就是基于js写的一个功能模块而已
特点:异步提交、局部刷新
- 浏览器窗口输入url回车 GET
- a标签href属性填写url点击 GET
- form表单 GET/POST
- Ajax GET/POST
$.ajax({
// 1.到底朝哪个后端提交数据
url:‘‘, // 控制数据的提交路径 有三种写法 跟form表单的action属性一致
// 2.指定当前请求方式
type:‘post‘,
// 3.提交的数据
data:{‘i1‘:$(‘#i1‘).val(),‘i2‘:$(‘#i2‘).val()},
// 4.ajax是异步提交 所以需要给一个回调函数来处理返回的结果
success:function (data) { // data就是异步提交的返回结果
// 将异步回调的结果通过DOM操作渲染到第三个input框中
$(‘#i3‘).val(data)
}
})urlencoded、formdata、application/json,前后端数据交互,编码格式与数据格式一定要一致
- urlencoded数据格式
默认是urlencoded编码格式传输数据,urlencoded数据格式:XXX=OOO&YYY=ZZZ,django后端针对该格式的数据,会自动解析并帮你打包到request.POST中
- formdata数据格式
django后端针对符合urlencoded编码格式数据(普通键值对)还是统一解析到request.POST中,而针对formdata文件数据就会自动解析放到request.FILES中
- urlencoded数据格式
ajax默认的也是urlencoded编码格式
- application/json
django后端针对json格式数据并不会做任何的处理,而是直接放在request.body中
$(‘#d2‘).on(‘click‘,function () {
$.ajax({
url:‘‘,
type:‘post‘,
// 修改content-Type参数
contentType:‘application/json‘, // json格式序列化
data:JSON.stringify({‘username‘:‘jason‘,‘password‘:123}), // 将数据序列化成json格式字符串
success:function (data) {
alert(data)
}
})
})ajax发送文件
使用内置对象FormData
$(‘#d3‘).click(function () {
// 1 需要先生成一个内置对象
var myFormData = new FormData();
// 2 传普通键值对 当普通键值对较多的时候 我们可以利用for循环来添加
myFormData.append(‘username‘,‘jason‘);
myFormData.append(‘password‘,123);
// 3 传文件
myFormData.append(‘myfile‘,$(‘#i1‘)[0].files[0]); // 获取input框内部用户上传的文件对象
// 发送ajax请求
$.ajax({
url:‘‘,
type:‘post‘,
data:myFormData,
// 发送formdata对象需要指定两个关键性的参数
processData:false, // 让浏览器不要对你的数据进行任何的操作
contentType:false, // 不要使用任何编码格式 对象formdata自带编码格式并且django能够识别该对象
success:function (data) {
alert(data)
}
})
})前后端数据交互一般情况下都是一个大字典
from app01 import models
from django.core import serializers
def ab_se(request):
user_queryset = models.Userinfo.objects.all()
# user_list = []
# for user_obj in user_queryset:
# user_list.append({
# ‘username‘:user_obj.username,
# ‘password‘:user_obj.password,
# ‘gender‘:user_obj.get_gender_display(),
# })
# res = jso n.dumps(user_list)
res = serializers.serialize(‘json‘,user_queryset)
return HttpResponse(res)def ab_bc(request):
# 先插入1000条件数据
# for i in range(1,1001):
# models.Book.objects.create(title=‘第%s本书‘%i)
book_list = []
for i in range(1,10001):
book_list.append(models.Book(title=‘新的%s书‘%i))
models.Book.objects.bulk_create(book_list) # 批量插入数据的方式
book_queryset = models.Book.objects.all()
return render(request,‘ab_bc.html‘,locals())使用方法:定义一个Pagination类
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=10, pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
用法:
queryset = model.objects.all()
page_obj = Pagination(current_page,all_count)
page_data = queryset[page_obj.start:page_obj.end]
获取数据用page_data而不再使用原始的queryset
获取前端分页样式用page_obj.page_html
"""
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
if current_page < 1:
current_page = 1
self.current_page = current_page
self.all_count = all_count
self.per_page_num = per_page_num
# 总页码
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager
self.pager_count = pager_count
self.pager_count_half = int((pager_count - 1) / 2)
@property
def start(self):
return (self.current_page - 1) * self.per_page_num
@property
def end(self):
return self.current_page * self.per_page_num
def page_html(self):
# 如果总页码 < 11个:
if self.all_pager <= self.pager_count:
pager_start = 1
pager_end = self.all_pager + 1
# 总页码 > 11
else:
# 当前页如果<=页面上最多显示11/2个页码
if self.current_page <= self.pager_count_half:
pager_start = 1
pager_end = self.pager_count + 1
# 当前页大于5
else:
# 页码翻到最后
if (self.current_page + self.pager_count_half) > self.all_pager:
pager_end = self.all_pager + 1
pager_start = self.all_pager - self.pager_count + 1
else:
pager_start = self.current_page - self.pager_count_half
pager_end = self.current_page + self.pager_count_half + 1
page_html_list = []
# 添加前面的nav和ul标签
page_html_list.append(‘‘‘
<nav aria-label=‘Page navigation>‘
<ul class=‘pagination‘>
‘‘‘)
first_page = ‘<li><a href="?page=%s">首页</a></li>‘ % (1)
page_html_list.append(first_page)
if self.current_page <= 1:
prev_page = ‘<li class="disabled"><a href="#">上一页</a></li>‘
else:
prev_page = ‘<li><a href="?page=%s">上一页</a></li>‘ % (self.current_page - 1,)
page_html_list.append(prev_page)
for i in range(pager_start, pager_end):
if i == self.current_page:
temp = ‘<li class="active"><a href="?page=%s">%s</a></li>‘ % (i, i,)
else:
temp = ‘<li><a href="?page=%s">%s</a></li>‘ % (i, i,)
page_html_list.append(temp)
if self.current_page >= self.all_pager:
next_page = ‘<li class="disabled"><a href="#">下一页</a></li>‘
else:
next_page = ‘<li><a href="?page=%s">下一页</a></li>‘ % (self.current_page + 1,)
page_html_list.append(next_page)
last_page = ‘<li><a href="?page=%s">尾页</a></li>‘ % (self.all_pager,)
page_html_list.append(last_page)
# 尾部添加标签
page_html_list.append(‘‘‘
</nav>
</ul>
‘‘‘)
return ‘‘.join(page_html_list)Pagination类
后端
current_page = request.GET.get(‘page‘, 1) all_count = book_queryset.count() # 1 现生成一个自定义分页器类对象 page_obj = Pagination(current_page=current_page,all_count=all_count,pager_count=9) # 2 针对真实的queryset数据进行切片操作 page_queryset = book_queryset[page_obj.start:page_obj.end] return render(request,‘ab_bc.html‘,locals())
前端
{% for book_obj in page_queryset %}
<p>{{ book_obj.title }}</p>
{% endfor %}
{{ page_obj.page_html|safe }}后端:
from django.http import JsonResponse
import time
def show_user(request):
"""
前后端如果是通过ajax进行交互 那么交互的媒介一般情况下都是一个字典
:param request:
:return:
"""
if request.method == ‘POST‘:
time.sleep(3)
back_dic = {"code":1000,‘msg‘:‘‘}
delete_id = request.POST.get(‘delete_id‘)
models.Userinfo.objects.filter(pk=delete_id).delete()
back_dic[‘msg‘] = ‘删除成功,准备跑路!!!‘
return JsonResponse(back_dic)
user_queryset = models.Userinfo.objects.all()
return render(request,‘show_user.html‘,locals())前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
{% load static %}
<link rel="stylesheet" href="{% static ‘dist/sweetalert.css‘ %}">
<script src="{% static ‘dist/sweetalert.min.js‘ %}"></script>
<style>
div.sweet-alert h2 {
padding-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2 class="text-center">数据展示</h2>
<table class="table-hover table table-striped">
<thead>
<tr>
<th>主键</th>
<th>用户名</th>
<th>密码</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for user_obj in user_queryset %}
<tr>
<td>{{ user_obj.pk }}</td>
<td>{{ user_obj.username }}</td>
<td>{{ user_obj.password }}</td>
<td>{{ user_obj.get_gender_display }}</td>
<td>
<a href="#" class="btn btn-primary btn-xs">编辑</a>
<a href="#" class="btn btn-danger btn-xs cancel" data_id="{{ user_obj.pk }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<script>
$(‘.cancel‘).click(function () {
var $aEle = $(this);
swal({
title: "你确定要删吗?",
text: "你如果删了,你可要准备跑路啊!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "是的,老子就要删!",
cancelButtonText: "惹不起惹不起!",
closeOnConfirm: false,
closeOnCancel: false,
showLoaderOnConfirm: true
},
function (isConfirm) {
if (isConfirm) {
// 发送ajax请求
$.ajax({
url:‘‘,
type:‘post‘,
data:{‘delete_id‘:$aEle.attr("data_id")},
success:function (data) { // 回调函数会自动将二进制的json格式数据 解码并反序列成js中的数据类型
if (data.code == 1000){
swal("删了!", "你准备跑路吧!", "success");
// 方式1
{#window.location.reload()#}
// 方式2 DOM操作动态修改
$aEle.parent().parent().remove() // 将标签直接移除
}else{
swal(‘发生了未知的错误‘, "error");
}
}
});
} else {
swal("怂笔", "你成功的刷新我对你的认知", "error");
}
});
})
</script>
</body>
</html> 结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
本文实例讲述了php+ ajax 实现的写入数据库操作。分享给大家供大家参考,具体如下:。<input class="tel" type="text" placeholder="请输入您的手机号码&q