Django入门到放弃之ajax

1.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'),

2.jax上传文件

固定模板

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)
            }
        })

form表单上传文件

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')

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
<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')

3.ajax提交json格式

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

4.json序列化时间日期类型的数据的方法

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)

5.django内置序列化器

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格式字符串

  

posted @   百衲本  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
历史上的今天:
2020-08-27 Linux 五种IO模型
cnblogs_post_body { color: black; font: 0.875em/1.5em "微软雅黑" , "PTSans" , "Arial" ,sans-serif; font-size: 15px; } cnblogs_post_body h1 { text-align:center; background: #333366; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 23px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h2 { text-align:center; background: #006699; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 20px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h3 { background: #2B6695; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 18px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } 回到顶部 博客侧边栏 回到顶部 页首代码 回到顶部 页脚代码
点击右上角即可分享
微信分享提示