ajax json用法 上传文件 登录

时间:2024-10-12 09:33:07
 1. json
  json  是一种数据结构  跨平台跨语言
  1. python中json数据的转换
   1.数据类型
    字符串 数字 布尔值 列表 字典 None
    
   2. 序列化  python的数据类型  ——》  json字符串
    json.dumps(python的数据类型) 
    json.dump(python的数据类型,f)
   3. 反序列化  json字符串     ——》  python的数据类型
    json.loads(json字符串)
    json.load(json字符串,f)
    
  2. js中json数据的转换
   1.数据类型
    字符串  数字 布尔值 数组 对象  null
    
   2. 序列化  js的数据类型  ——》  json字符串
    JSON.stringify(js的数据类型)
    
   3. 反序列化  json字符串 ——》 JS的数据类型
    JSON.parse(json字符串)
    
  3. from django.http import JsonResponse    一般用来转换成字符串   字典就用这种方法
  JsonResponse({}) 
     JsonResponse([],safe=False)        传列表加这个参数
 2. ajax上传文件  及登录
视图代码:
# 上传文件
def upload(request):
    if request.is_ajax():
        f1 = request.FILES.get('f1')
        with open(f1.name, 'wb') as f:
            for i in f1.chunks():
                f.write(i)
        return HttpResponse('上传成功')
    return render(request, 'upload.html')
html代码:
<input type="file" id="my_file">
<button id="b1">上传</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/static/ajax_setup.js"></script>
<script>
    $('#b1').click(
        function () {
            var form_obj = new FormData();
            form_obj.append('f1', $('#my_file')[0].files[0]);
            $.ajax({
                url: '/upload/',
                type: 'post',
                data: form_obj,
                processData: false,
                contentType: false,
                success: function (res) {
                    console.log(res)
                }
            })
        }
    )   
 
ajax登录代码
  # 登陆
from django.views import View
from django.http import JsonResponse
class Log(View):
    def get(self,request):
        return render(request,'log.html')
    def post(self,request):
        # 传一个字典
        ret={'status':0,'msg':''}
        user=request.POST.get('user')
        pwd=request.POST.get('pwd')
        # 找到第一个  不要用[0] 来取
        obj=models.User.objects.filter(name=user,pwd=pwd).first()
        if obj:
            # 给字典添加一个 登陆状态 及跳转网址
            ret['url']='/upload/'
            # 因为是字典新式 用JsonResponse
            return JsonResponse(ret)
        else:
            # 给字典添加  1为和设置用户密码错误
            ret['status']=1
            ret['msg'] = '用户名或密码错误'
            return JsonResponse(ret)
html代码:   
<p>
    用户名:<input type="text" id="user">
</p>
<p>
    密码:<input type="password" id="pwd">
</p>
<button id="b1">登录</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/static/ajax_setup.js"></script>
<script>
$('#b1').click(function () {
    $.ajax({
        url:'/log/',
        type:'post',
        data:{
            user:$('#user').val(),
            pwd:$('#pwd').val()
        },
        success:function (res) {
            {#res 是调回来的对象 #}
            if (res.status ==0){
                {# res.url 相当于取字典里的值#}
                location.href = res.url
            }
            else {
                    alert(res.msg)
        }
        }
    })
})