• Ajax之基本语法


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

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

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

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

    【1】form表单

    • 前后端传输数据的格式

      • urlencoded

      • formdata

      • json

    【2】编码格式

    • form表单默认的编码格式是urlencoded
      • 通过查看请求头中的 Content-Type 参数
    1. 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
    2. Accept-Encoding:gzip, deflate, br
    3. Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
    4. Cache-Control:no-cache
    5. Connection:keep-alive
    6. Content-Length:27
    7. Content-Type:application/x-www-form-urlencoded
    • 携带数据格式
    username=666666&password=66
    • Django后端针对 urlencoded 编码格式的数据会自动帮我们解析封装到 request.POST 中

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

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

    【3】Ajax

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

    【4】代码演示

    • 后端
    1. def index(request):
    2. if request.method == 'POST':
    3. print(request.POST)
    4. print(request.FILES)
    5. return render(request, 'index.html')
    • 前端HTML
    1. <form action="" method="post" enctype="multipart/form-data">
    2. <p>username: <input type="text" name="username" class="form-control">p>
    3. <p>password: <input type="password" name="password" class="form-control">p>
    4. <p>file: <input type="file">p>
    5. <p><input type="submit" class="btn btn-success">p>
    6. <p><input type="button" class="btn btn-danger" value="按钮" id="d1">p>
    7. form>
    8. <script>
    9. $("#d1").click(function () {
    10. $.ajax({
    11. url: '',
    12. type: 'POST',
    13. data: {"username": "dream", "password": 1314521},
    14. success: function (args) {
    15. },
    16. })
    17. })
    18. script>

    【二】Ajax发送JSON格式数据

    前后端传输数据的时候一定要保证编码格式数据与真正的数据格式是一致的

    {"username":"kevin", "password":123}  它不符合urlencoded格式的数据

    • 前端
    1. $.ajax({
    2. url:'',
    3. type:'post',
    4. data:JSON.stringify({a:1, b:2}), // 序列化的 "{"a":1, "b":2}"
    5. contentType:'application/json', // json格式的
    6. success:function (res) {
    7. }
    8. })
    • 后端
    1. def index(request):
    2. if request.method == 'POST':
    3. request.POST只能接收post请求的符合urlencoded编码格式的数据 {}
    4. print(request.POST) #
    5. print(request.body) # b'{"a":1,"b":2}'
    6. json_bytes=request.body # 接收浏览器发过来的纯原生的数据,二进制,需要自己做封装处理
    7. json_str=json_bytes.decode('utf-8') # {"a":1,"b":2}
    8. print(json_str, type(json_str))
    9. import json
    10. json_dict = json.loads(json_str)
    11. print(json_dict, type(json_dict)) # {'a': 1, 'b': 2}
    12. json_dict=json.loads(json_bytes) # 最好不要省略
    13. print(json_dict, type(json_dict)) # {'a': 1, 'b': 2}
    14. return render(request, 'index.html')

    【三】Ajax发送文件数据

    • Ajax发送文件数据需要借助js内置对象formdata

    • 前端

    1. <script>
    2. $(".btn").click(function (ev) {
    3. console.log(123);
    4. // 要获取到文件数据,
    5. {#console.log($("#myfile")[0].files[0]) // C:\fakepath\123.png#}
    6. // 提交文件数据需要借助于formdata对象
    7. var myFormDataObj = new FormData;
    8. var username = $("#username").val();
    9. var myfile = $("#myfile")[0].files[0];
    10. myFormDataObj.append('username', username);
    11. myFormDataObj.append('myfile',myfile);
    12. $.ajax({
    13. url: '',
    14. type: 'post',
    15. {#data: JSON.stringify({a: 1, b: 2}), // 序列化的 "{"a":1, "b":2}"#}
    16. data: myFormDataObj, // 序列化的 "{"a":1, "b":2}"
    17. {#contentType: 'application/json', // json格式的#}
    18. contentType:false, // 告诉浏览器不要给我的编码格式做任何的处理
    19. processData: false, //
    20. success: function (res) {
    21. }
    22. })
    23. })
    24. script>
    • 后端
    1. def ab_file(request):
    2. if request.is_ajax():
    3. if request.method == 'POST':
    4. print('POST::>>', request.POST)
    5. # 普通键值对放在了 request.POST 中
    6. # POST::>>
    7. print('FILES::>>', request.FILES)
    8. # 文件数据放在了 request.FILES 中
    9. # FILES::>> ]}>
    10. return render(request, 'ab_file.html')
    Ajax结合layer弹窗实现二次确认

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

  • 相关阅读:
    [OpenCV实战]52 在OpenCV中使用颜色直方图
    榕树贷款C++ STL 中没有内置 CSV 读取器/写入器
    【基于langchain + streamlit 完整的与文档对话RAG】
    【牛牛前端面试每天练】一,HTML与CSS专项
    认真研究ConcurrentHashMap中的元素统计策略
    Java代码审计15之Apache log4j2漏洞
    duilib 入门基础十二 样式类
    Linux基础系列(四)——Homebrew
    Drools规则属性,高级语法
    从零开始Blazor Server(10)--编辑角色
  • 原文地址:https://blog.csdn.net/m0_71292438/article/details/134534336