http请求contentype详解

请求头

在http请求头中有一项重要的参数就是contentype,用来告诉浏览器,我服务器传送过来的数据是什么格式,这样浏览器才知道怎么去解析服务器传过来的数据

urlencoded

通常我们form表单提交的数据都是urlencoded格式的数据,这个格式的数据,django会自动解析并放在request.POST中。
看下面实例:
有login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/core.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<form action="" method="post" enctype="application/x-www-form-urlencoded">
    <label for="inp-user">用户名</label>
    <input type="text" name="user" id="inp-user">
    <label for="inp-pwd">密码</label>
    <input type="text" id="inp-pwd" name="pwd">
    <button type="submit">提交</button>
</form>
<button id="aj">ajax</button>
<script>
    $('#aj').on('click',function () {
        $.ajax(
            {
                url:'',
                data:JSON.stringify({'user':'kingfan','pwd':'123'}),
                type:'post',
                contentType:'json',
                success:function (ret) {
                    console.log(ret)
                }
            }
        )
    })
</script>
</body>
</html>

1456462-20190121205330966-830206397.png
后端代码:

from django.shortcuts import render,HttpResponse

# Create your views here.

def login(request):
    if request.method=='GET':
        return render(request,'login.html')
    else:
        print(request.POST)
        print(request.body)
        return HttpResponse('ok')

1456462-20190121205535565-378118022.png
在看看请求头:
1456462-20190121205643794-558455521.png

ajax的json请求

ajax在没指定contentype的情况下默认也是urlencode数据,指定为json后就是json数据,记得对应的data也要是json数据
点击页面的ajax按钮发送数据
1456462-20190121205849070-1669806954.png
1456462-20190121210004213-814529718.png

可以看出django无法解析json数据,原始数据在request.body中,我们可以手动利用json数据解析

转载于:https://www.cnblogs.com/Kingfan1993/p/10300978.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值