ajax

mutipart Django默认有解释器 upload ajax 提交的时候

form提交的是 自己写的multipart/form-data 可以解释

1 http发送数据三种格式

enctype = 'mfd'告诉http协议,请求后端服务端的时候,发送的请求体里面的格式是multipart/form-data,这个格式发送的是片段数据,content-type

form 三种提交数据的方式
http:
		content-type(请求头)   view sorse
			作用以什么规范来加工
content-type:			
1 application/x-www-form-urlencoded
 		&符拼接的 一个键对应一个值
 	get url+数据
 	post 请求体
 	
后端:
	if request.META.get('content-type') == 'urlencoded':
	request.body.split('&')   ##[name=xx,pwd=ss]
	---request.POST[]或者GET[]	放到里面

2 multipart/form-data
		 ##分片发送  
         ---request.FILES
3 appliaction/json	
django 不支持  没有内置的关于json的解释器  需要自己解析
		##{'name':xxx,'pwd':ssss}
		---没有对应的解析器	数据在body里
		拿原始数据  自己反序列化

前后端分离	前端发送  不是ajax而是absors  默认json
Django 	drf 专门做数据接口的

js json python

python解析成json dumps

js JSON.parse(res); 解析了

自己解析

  {#  var res1 = JSON.parse(res);#}
              {#alert(res1.status);#}
              {#alert(res1.info);#}

3 json和Django 数据类型 基本上是一一对应的

除了datetime 和date的

解决方法:

#对含有日期格式数据的json数据进行转换
class JsonCustomEncoder(json.JSONEncoder):      # json的序列化器
    def default(self, field):
        if isinstance(field,datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field,date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self,field)
d1 = datetime.now()
dd = json.dumps(d1,cls=JsonCustomEncoder)
print(dd)

往前端传输数据,最好是列表,别的还得找键

Python json js
dict object 自定义对象
list array array

今日内容回顾

ajax文件上传

form文件上传 form enctype = 'mutiple-form'

views:

​ request.FILES.get(‘标签name值’)

ajax文件上传

var formdata = new FormData();

formdata.append('file_obj',$('input[type=file][0].files[0]'));

formdata.append('csrfmiddlewaretoken',$('[name=csrfmiddlewaretoken]').val());

formdata.append('username',$('[name=username]').val());

$.ajax({

url:'路径',

type:'post',

data : formdata,

processData:false;

contentType:false;

success:function(res){}

})

request.FILES.get('file_obj')

file_obj = request.FILES.get('file_obj')

with open(file_obj.name,'wb')as f:

for data in file_obj:

​ f.write(data)

for cc in file_obj.chunks():

​ f.write(cc)

contenttype

三种类型

响应方法

HttpResponse('xxx')
HttpResponse(json.dups({'name':'xxx'}),content_type='app/json')
JsonResponse({'name':'liu'})
JsonResponse(其他类型,safe = False)


序列化
  # 建议这种方式使用序列化
 book_o = models.Book.objects.all().values('title','price')
 books = list(book_o)
 print(books)        #[{'title': '三体', 'price': 22}]
 
时间日期序列化

json

返回页面

var url = res.url:
location.href = url;
{#        location 跳转页面  dom:1个定时器 一个location#}
原文地址:https://www.cnblogs.com/Doner/p/10948947.html