Ajax之基本语法

【一】前后端传输数据的编码格式(contentType)

主要研究POST请求数据的编码格式

因为GET请求数据就是直接放在url后面的

  • 可以朝后端发送post请求的方式
    • form请求
    • ajax请求
    • api工具

【1】form表单

  • 前后端传输数据的格式

    • urlencoded

    • formdata

    • json

【2】编码格式

  • form表单默认的编码格式是urlencoded
    • 通过查看请求头中的 Content-Type 参数
python 复制代码
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:27
Content-Type:application/x-www-form-urlencoded
  • 携带数据格式
python 复制代码
username=666666&password=66
  • Django后端针对 urlencoded 编码格式的数据会自动帮我们解析封装到 request.POST 中

  • 如果编码格式改为 formdata ,那么针对普通的键值对还是解析到 request.POST 中,而其他文件格式的数据解析到 request.FILES 中

  • form表单无法发送json格式数据

【3】Ajax

python 复制代码
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:31
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
  • 默认的编码格式是 urlencoded
  • 数据格式
python 复制代码
username=dream&password=1314521
  • Django后端针对 urlencoded 编码格式的数据会自动帮我们解析封装到 request.POST 中 --->username=dream&password=1314521

【4】代码演示

  • 后端
python 复制代码
def index(request):
    if request.method == 'POST':
        print(request.POST)
        print(request.FILES)
    return render(request, 'index.html')
  • 前端HTML
html 复制代码
<form action="" method="post" enctype="multipart/form-data">
    <p>username: <input type="text" name="username" class="form-control"></p>
    <p>password: <input type="password" name="password" class="form-control"></p>
    <p>file: <input type="file"></p>
    <p><input type="submit" class="btn btn-success"></p>
    <p><input type="button" class="btn btn-danger" value="按钮" id="d1"></p>
</form>
 
<script>
    $("#d1").click(function () {
        $.ajax({
            url: '',
            type: 'POST',
            data: {"username": "dream", "password": 1314521},
            success: function (args) {
 
            },
        })
    })
</script>

【二】Ajax发送JSON格式数据

前后端传输数据的时候一定要保证编码格式数据与真正的数据格式是一致的
{"username":"kevin", "password":123} 它不符合urlencoded格式的数据

  • 前端
html 复制代码
$.ajax({
              url:'',
              type:'post',
              data:JSON.stringify({a:1, b:2}), // 序列化的     "{"a":1, "b":2}"
              contentType:'application/json', // json格式的
              success:function (res) {

              }
          })
  • 后端
python 复制代码
def index(request):
    if request.method == 'POST':
        request.POST只能接收post请求的符合urlencoded编码格式的数据 {}
        print(request.POST) # <QueryDict: {}>
        print(request.body) # b'{"a":1,"b":2}'
        json_bytes=request.body # 接收浏览器发过来的纯原生的数据,二进制,需要自己做封装处理
        json_str=json_bytes.decode('utf-8')  # {"a":1,"b":2} <class 'str'>
        print(json_str, type(json_str))
        import json
        json_dict = json.loads(json_str)
        print(json_dict, type(json_dict)) # {'a': 1, 'b': 2} <class 'dict'>
        json_dict=json.loads(json_bytes) # 最好不要省略
        print(json_dict, type(json_dict))  # {'a': 1, 'b': 2} <class 'dict'>

    return render(request, 'index.html')

【三】Ajax发送文件数据

  • Ajax发送文件数据需要借助js内置对象formdata
  • 前端
html 复制代码
<script>
    $(".btn").click(function (ev) {
        console.log(123);
        // 要获取到文件数据,
        {#console.log($("#myfile")[0].files[0]) // C:\fakepath\123.png#}
        // 提交文件数据需要借助于formdata对象
        var myFormDataObj = new FormData;
        var username = $("#username").val();
        var myfile = $("#myfile")[0].files[0];
        myFormDataObj.append('username', username);
        myFormDataObj.append('myfile',myfile);

        $.ajax({
            url: '',
            type: 'post',
            {#data: JSON.stringify({a: 1, b: 2}), // 序列化的     "{"a":1, "b":2}"#}
            data: myFormDataObj, // 序列化的     "{"a":1, "b":2}"
            {#contentType: 'application/json', // json格式的#}
            contentType:false, // 告诉浏览器不要给我的编码格式做任何的处理
            processData: false, //
            success: function (res) {

            }
        })
    })
</script>
  • 后端
python 复制代码
def ab_file(request):
    if request.is_ajax():
        if request.method == 'POST':
            print('POST::>>', request.POST)
            # 普通键值对放在了  request.POST   中
            # POST::>> <QueryDict: {'username': ['dream'], 'password': ['666']}>
            print('FILES::>>', request.FILES)
            # 文件数据放在了  request.FILES   中
            # FILES::>> <MultiValueDict: {'myfile': [<InMemoryUploadedFile: img.png (image/png)>]}>
 
    return render(request, 'ab_file.html')
Ajax结合layer弹窗实现二次确认

https://layuiweb.com/layer/index.htm

相关推荐
要加油哦~6 分钟前
css | class中 ‘.‘ 和 ‘:‘ 的使用 | 如,何时用 &.is-selected{ ... } 何时用 &:hover{...}?
前端·css
不浪brown37 分钟前
开源!矢量建筑白模泛光特效以及全国77个大中城市的矢量shp数据获取!
前端·cesium
山有木兮木有枝_39 分钟前
JavaScript 数据类型与内存分配机制探究
前端
小小小小宇44 分钟前
前端 异步任务并发控制
前端
bysking1 小时前
【27-vue3】vue3版本的"指令式弹窗"逻辑函数createModal-bysking
前端·vue.js
LuckySusu1 小时前
【HTML篇】script`标签中的 defer 与 async:深入解析异步加载 JavaScript 的差异
前端·html
CAD老兵1 小时前
在 TypeScript 中复用已有 Interface 的部分属性:完整指南
前端
一头小鹿1 小时前
【JS】原型和原型链 | 笔记整理
javascript
龚思凯1 小时前
Vue 3 中 watch 监听引用类型的深度解析与全面实践
前端·vue.js
于冬恋1 小时前
Web后端开发(请求、响应)
前端