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数据解析

  • 相关阅读:
    linux实践——内核编程 基础模块
    linux内核分析 课程总结
    linux内核分析 期中总结
    linux内核分析 第八周
    linux内核分析 第4章读书笔记
    linux内核分析 第七周
    2020JAVA面试题
    springboot redis工具类
    mysql关于时间函数的应用
    jetty的web部署
  • 原文地址:https://www.cnblogs.com/Kingfan1993/p/10300978.html
Copyright © 2011-2022 走看看