python到JavaScript
先通过json.dumps() 序列化后在传输到javascript,JavaScript接受到JSON格式字符串后通过JSON.parse()进行解析。
JavaScript到python
先通过JSON.Stringfy()序列化后再传输到python,python接受到JSON格式字符串后,通过json.loads()进行反序列化解析,得到数据。
1 var formdata = new FormData(); 2 formdata.append('user',$('#username').val()) 3 formdata.append('csrfmiddlewaretoken',$('#csrfmiddlewaretoken').val()) 4 formdata.append('file',$('#file')[0].files[0]) 5 $.ajax({ 6 url:'/upload/', 7 type:'post', 8 data:formdata, 9 success:function(response){ 10 response 11 12 } 13 14 }) 15 16 def upload(request): 17 if request.method == 'GET': 18 19 return render(request,'upload.html') 20 else: 21 print(request.POST) #拿到的是post请求的数据,但是文件相关数据需要用request.FILES去拿 22 print(request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}> 23 file_obj = request.FILES.get('head-pic') 24 print(file_obj) 25 file_name = file_obj.name 26 27 28 # f = open('xx.txt','rb') 29 # with open('xx.txt','wb') as f2: 30 # for i in f: 31 # f2.write(i) 32 import os 33 path = os.path.join(settings.BASE_DIR,'statics','img',file_name) 34 with open(path,'wb') as f: 35 for i in file_obj: 36 f.write(i) 37 #for chunk in file_obj.chunks(): 38 # f.write(chunk) 39 40 return HttpResponse('ok')
1 def index(request): 2 3 d1 = {'name':'chao'} 4 5 import json 6 7 return HttpResponse(json.dumps(d1)) -- success:function(res){ var a = JSON.parse(res) } 8 9 return HttpResponse(json.dumps(d1),content-type='application/json') --success:function(res){res--自定义对象,不需要自己在反序列化了} 10 11 return JsonResponse(d1) 12 13 d1 = [11,22] #非字典类型的数据都需要加safe=False 14 15 return JsonResponse(d1,safe=False)
获取多对多数据的时候 1 authors = request.POST.getlist('authors')
1 import json 2 from datetime import datetime 3 from datetime import date 4 5 #对含有日期格式数据的json数据进行转换 6 class JsonCustomEncoder(json.JSONEncoder): 7 def default(self, field): 8 if isinstance(field,datetime): 9 return field.strftime('%Y-%m-%d %H:%M:%S') 10 elif isinstance(field,date): 11 return field.strftime('%Y-%m-%d') 12 else: 13 return json.JSONEncoder.default(self,field) 14 15 16 d1 = datetime.now() 17 18 dd = json.dumps(d1,cls=JsonCustomEncoder) 19 print(dd)