zoukankan      html  css  js  c++  java
  • 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>
    


    后端代码:

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


    在看看请求头:

    ajax的json请求

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

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

  • 相关阅读:
    Tensorflow的对二次函数的神经网络训练
    ubuntu16.04的Anaconda下的tensorflow安装py3.5
    数字信号处理C语言(3) ------FFT
    数字信号处理C语言(2) ------带高斯噪声的sin函数和组合sin函数
    数字信号处理C语言(1) ------均匀分布和高斯分布随机数
    CCIE学习笔记 ----TSHOOT
    CCIE学习笔记 ----BGP
    CCIE学习笔记 ----GRE over IPsec
    调试
    Java protobuf框架使用向导
  • 原文地址:https://www.cnblogs.com/Kingfan1993/p/10300978.html
Copyright © 2011-2022 走看看