一.Ajax
1.过程:页面发出请求-->
调用视图函数-->
展示页面,在页面中提交Ajax请求-->
调用Ajax视图函数,返回JsonRespon(dic)-->
将dic传入success()中-->
返回响应
2.语法:
$.ajax({
参数1:值1,
参数2:值2,
参数3:值3,
...
})
常用参数:url,type,data,error,success
3.get请求和post请求
get请求可以将参数拼接到url后面
post不行,而且请求时需要携带csrf_token值
data:{'csrfmiddlewaretoken':'{{csrf_token}}'}
4.使用ajax提交文件
view:
def index4(request):
return render(request, 'index4.html')
def index4_ajax(request):
image_obj = request.FILES.get('pic')
with open('1.jpg', mode='wb')as f:
for content in image_obj.chunks():
f.write(content)
dic = {'status': 'true'}
return JsonResponse(dic)
index4.html:
{% load static %}
<script src="{% static 'jquery-3.3.1.js' %} "></script>
<body>
<h2>文件上传</h2>
{% csrf_token %}
<p>
图片: <input type="file" name="pic" id="pic">
</p>
<button id="btn">点击上传</button>
<script>
$(function(){
$('#btn').click(function () {
var formData = new FormData();
formData.append('pic',document.getElementById('pic').files[0]);
formData.append('csrfmiddlewaretoken','{{ csrf_token }}');
$.ajax({
url:'/index4_ajax/',
type:'POST',
data:formData,
processData: false,
contentType:false,
success:function (res) {
alert('上传成功...')
}
})
})
})
</script>
</body>
二.MVC和MTV模式
1.MVC:
M:model模型,与数据库交互
V:view视图,产生html页面
C:controller控制器,接受请求,进行处理,与M和V进行交互
2.MTV:
django里的
M:model模型,与数据库交互
T:template模板,产生html页面
View视图,负责业务逻辑,调用model和template,返回响应