Django入门到放弃之ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 特性: 1. 异步请求 2. 局部刷新 # 登录认证 $.ajax({ url: '/login/' , #请求路径 type : 'post' , #请求方式 data:{ username:$( '#username' ).val(), password:$( '#password' ).val(), }, # 后端返回什么response就是什么 success:function(response){ # response 响应内容 var resStr = JOSN.parse(respone); #将响应内容序列化 # {"aa":0,"bb":"/index/"} if (resStr[ 'aa' ] = = = 0 ){ locaction.href = resStr[ 'bb' ]; location.href = '/index/' ; #利用location实现页面跳转 } else { ... } }, # 请求失败时触发error执行,并将错误信息给error error:function(error){ xxxxx } }) view.py class LoginView(View): def get( self ,request): return render(request, 'login.html' ) def post( self ,request): name = request.POST.get( 'uname' ) pwd = request.POST.get( 'pwd' ) if name = = 'bge' and pwd = = '213' : ret = '{"code":0,"msg":"登录成功"}' return HttpResponse(ret) else : # return redirect(reverse('login')) ret = '{"code":3,"msg":"用户名或密码错误"}' return HttpResponse(ret) urls.py path( 'login/' , views.LoginView.as_view(),name = 'login' ), |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 1 http请求,body体中放文件内容,ajax本质就是发送http请求,所以它可以上传文件 2 两种上传文件的方式,form表单,ajax 3 固定模板 var formdata = new FormData() formdata.append( 'myfile' ,$( "#id_file" )[ 0 ].files[ 0 ]) # 还可以带数据 $.ajax({ url: '/uploadfile/' , method: 'post' , / / 上传文件必须写这两句话 processData:false, # 预处理数据, contentType:false, # 不指定编码,如果不写contentType,默认用urlencoded data:formdata, # formdata内部指定了编码,并且自行处理数据 success:function (data) { console.log(data) } }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | upload.html <form action = "/upload/" method = "post" enctype = "multipart/form-data" > { % csrf_token % } 头像:< input type = "file" name = "head-pic" > 用户名:< input type = "text" name = "username" > < input type = "submit" value = "提交" > < / form> <hr> <hr> ajax文件上传: < input type = "file" id = "file" > ajax用户名 < input type = "text" id = "uname" > <button id = "btn" >提交< / button> view.py def upload(request): if request.method = = 'GET' : return render(request, 'uplaod.html' ) else : print (request.POST) print (request.FILES) file_obj = request.FILES.get( 'head-pic' ) print (file_obj) print (file_obj.name) path = os.path.join(settings.BASE_DIR, 'static' , 'image' ) file_path = os.path.join(path,file_obj.name) with open (file_path, 'wb' ) as f: # for i in file_obj: # f.write(i) for chunk in file_obj.chunks(chunk_size = 65535 ): #默认为65535b f.write(chunk) return HttpResponse( 'ok' ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <script src = "/static/jquery-3.3.1/jquery-3.3.1.js" >< / script> <script> $( '#btn' ).click(function () { var formdata = new FormData(); #ajax上传文件的时候,需要这个类型,它会将添加给它的键值对加工成formdata的类型 formdata.append( 'name' ,$( '#uname' ).val()); #添加键值的方法是append,注意写法,键和值之间是逗号 formdata.append( 'file_obj' , $( '#file' )[ 0 ].files[ 0 ]); formdata.append( 'csrfmiddlewaretoken' ,$( '[name=csrfmiddlewaretoken]' ).val()); $.ajax({ url: '/upload/' , type : 'post' , data: formdata, #将添加好数据的formdata放到data这里 processData:false, / / 不处理数据 contentType:false, / / 不设置内容类型 success: function (res) { console.log(res) } }) }) < / script> def upload(request): if request.method = = 'GET' : return render(request, 'uplaod.html' ) else : print (request.POST) #拿到的是post请求的数据,但是文件相关数据需要用request.FILES去拿 print (request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}> file_obj = request.FILES.get( 'file_obj' ) print (file_obj) print (file_obj.name) path = os.path.join(settings.BASE_DIR, 'static' , 'image' ) file_path = os.path.join(path,file_obj.name) with open (file_path, 'wb' ) as f: #可以通过循环文件句柄或通过chunks方法获取文件数据 # for i in file_obj: # f.write(i) for chunk in file_obj.chunks(chunk_size = 65535 ): #默认为65535b f.write(chunk) return HttpResponse( 'ok' ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | $.ajax({ url: '/uploajson/' , / / 写全,是什么样就写什么样 method: 'post' , contentType: 'application/json' , / / data要是json格式字符串 / / data: '{"name":"","password":""}' , / / 把字典转成json格式字符串 / / JSON.stringify(dic) / / 把json格式字符串转成对象 / / JSON.parse(data) data:JSON.stringify({name:$( "#id_name1" ).val(),password:$( "#id_password1" ).val()}), success:function (data) { / / 返回字符串类型,需要转成js的对象,字典 / / 1 如果:django 返回的是HttpResponse,data是json格式字符串,需要自行转成字典 / / 2 如果:django 返回的是JsonResponse,data是就是字典 / / ajax这个方法做的是,如果响应数据是json格式,自动反序列化 console.log(typeof data) var res = JSON.parse(data) console.log(typeof res) console.log(res.status) console.log(res.msg) } }) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def data(request): l1 = [ 11 , 22 , 33 ] res = request.GET.get( 'k1' ) print (request.get_full_path()) print (request.body) return JsonResponse(l1,safe = False ) #注意,非字典类型的数据都需要加safe=False |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import json from datetime import datetime from datetime import date #对含有日期格式数据的json数据进行转换 class JsonCustomEncoder(json.JSONEncoder): 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) |
1 2 3 4 5 | # 把对象转成json格式,json.dumps实现不了, # django内置了一个东西,可以把对象转成json格式 from django.core import serializers book_list = Book.objects. all () ret = serializers.serialize( "json" , book_list) # ret就是json格式字符串 |
"一劳永逸" 的话,有是有的,而 "一劳永逸" 的事却极少
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
2020-08-27 Linux 五种IO模型