ajax的json格式数据

什么是Ajax:

         通过js语言跟后台进行交互的一个东西

                   -特点:异步,局部刷新

                  

                   ajax往后台提交数据

                   $.ajax({

                            url:'请求的地址',

                            type:'get/post',

                            data:{key:value,key2:value2},

                            success:function(data){

                                     alert(data)

                            }

                   })

                           

        

         1 后台返回json格式

         2 问?返回render,返回redirect?

        

         基于ajax写一个登陆功能,一旦登陆成功,跳转到百度,登陆失败,在页面显示用户名或密码错误

        

         总结:

                   1 后端如果返回JsonResponse,前端的ajax内部会自动将json格式字符串转换成字典

                   2 后端如果返回HttpResponse,前端的ajax内部不会给你自动转换,拿到的data是字符串类型,需要手动JSON.parse(data)来转成字典

        

                   3 字符串转字典:JSON.parse(data)

                     字典转字符串:aa=JSON.stringify(字典对象)

                   4 如果前端传的格式是json格式,django不会处理body中的内容,需要自己处理

                     只有前端传的格式是urlencoded,form-data格式,django才会给我处理

 前段:
$('.btn').click(function () { data1={name:$('.name').val(),pwd:$('.pwd').val()}; $.ajax({ url:'/login/', type:'post', contentType:'application/json', data:JSON.stringify(data1), {#data:data1,#} success:function (data) { $('.p1').text(data.msg) } }) })

 

后台:
def login(request): #
if request.method == 'GET': # return render(request, 'login.html') if request.method == 'POST': # print(request.POST) # print(request.body) # data = request.body.decode('utf-8') # data = json.loads(data) # print(type(data)) # # name=data.get('name') # # pwd=data.get('pwd') # name = data['name'] # pwd = data['pwd'] # user = models.User.objects.filter(name=name, # pwd=pwd).first() # # if user: # dic = {'msg': '登陆成功'} # return JsonResponse(dic) # else: # dic = {'msg': '登录失败'} # return JsonResponse(dic)

 

 

前段: 
$('#submit').click(function () {
    $.ajax({
        url:'/login/',
        type:'post',
        data:{name1:$("#name").val(),pwd2:$("#pwd").val()},
        success:function (data) {
            //后台用JsonResponse返回数据
            //data 就会被转成字典
            console.log(data)
            console.log(typeof data)
            //JSON.parse(data) 把字符串类型转成字典
            data=JSON.parse(data)
            {#JSON.stringify()#}
            console.log(typeof dat1)
            if(data.status == 100){
                //成功,跳转到指定页面
                //location.href=地址,前端就会跳转到指定的url
                alert(data.msg)
                //$("#error").text(data.msg+'正在跳转')
                //location.href=data.url
            }else{
                $("#error").text(data.msg)
            }
        }
    })
})

 

 

def login(request):
    dic={'status':100,'msg':None}
    if request.method == 'GET':
        return render(request, 'login.html')
    # if request.is_ajax():
    if request.method=='POST':
        name=request.POST.get('name1')
        pwd=request.POST.get('pwd2')
        if name=='lqz' and pwd=='123':
            dic['msg'] = '登陆成功'
            # 想让前端跳转
            # dic['url']='http://www.baidu.com'
            dic['url']='/test/'
        else:
            # 返回json格式字符串
            dic['status']=101
            dic['msg']='用户名或密码错误'
        # return JsonResponse(dic)
        return HttpResponse(json.dumps(dic))

 

posted @ 2019-01-17 22:27  彼岸花纽约  阅读(10103)  评论(0编辑  收藏  举报