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

  • 相关阅读:
    RMI几种公布和引用服务的方式
    mysql 多日志表结果集合拼接存储过程
    USRP通信的结构体和常量(上位机、下位机共用)
    Flash Builder4破解步骤
    leetcode 217 Contains Duplicate 数组中是否有反复的数字
    关于权限表的基本设计
    Objective-C之成魔之路【7-类、对象和方法】
    vs2008C1902程序数据库管理不匹配
    配置hadoop集群一
    BZOJ 2338 HNOI2011 数矩形 计算几何
  • 原文地址:https://www.cnblogs.com/Kingfan1993/p/10300978.html
Copyright © 2011-2022 走看看