• Django与Ajax


    Ajax是什么

    Ajax是一种用于创建交互式Web应用程序的技术。它是Asynchronous JavaScript and XML的缩写,意思是使用JavaScript和XML进行异步数据交换。通过Ajax技术,可以在不刷新整个页面的情况下更新页面的某个部分或者获取服务器数据,并能够动态地将这些数据加入到页面中。Ajax被广泛应用于许多网站和Web应用程序中,已经成为Web开发的重要一环。

    AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。

    • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
    • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

    AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程想)

    优点

    • AJAX使用Javascript技术向服务器发送异步请求
    • AJAX无须刷新整个页面

    基于jquery的Ajax实现 

    1. <button class="send_Ajax">send_Ajaxbutton>
    2. <script>
    3. $(".send_Ajax").click(function(){
    4. $.ajax({
    5. url:"/handle_Ajax/",
    6. type:"POST",
    7. data:{username:"Yuan",password:123},
    8. success:function(data){
    9. console.log(data)
    10. },
    11.       
    12. error: function (jqXHR, textStatus, err) {
    13. console.log(arguments);
    14. },
    15. complete: function (jqXHR, textStatus) {
    16. console.log(textStatus);
    17. },
    18. statusCode: {
    19. '403': function (jqXHR, textStatus, err) {
    20. console.log(arguments);
    21. },
    22. '400': function (jqXHR, textStatus, err) {
    23. console.log(arguments);
    24. }
    25. }
    26. })
    27. })
    28. script>

    Ajax—->服务器——>Ajax执行流程图

     Ajax案例

    通过Ajax,实现前端输入两个数字,服务器做加法,返回到前端页面

    views模块

    1. from django.shortcuts import render,HttpResponse
    2. from django.http import JsonResponse
    3. import json
    4. # Create your views here.
    5. def ab_ajax(request):
    6. # if request.is_ajax():
    7. if request.method == "POST":
    8. print(request.POST)
    9. d1 = request.POST.get('inp1') # str
    10. d2 = request.POST.get('inp2') # str
    11. d3=int(d1)+int(d2)
    12. print(d3)
    13. json.dumps(d3)
    14. return HttpResponse(json.dumps(d3))#序列化
    15. #想返回一个字典
    16. #user_dict={"username":"kevin","password":123}#第二部分
    17. #return HttpResponse(json.dumps(user_dict))#第二部分
    18. #return JsonResponse(user_dict)# 后端用JsonResponse不用反序列化#第二部分
    19. return render(request, 'ab_ajax.html')

    templates\ab_ajax.html模块

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    7. <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    8. <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    9. </head>
    10. <body>
    11. {#ajax的三种序列化情况#}
    12. <input type="text" id="inp1">
    13. <input type="text" id="inp2">
    14. <input type="text" id="inp3">
    15. <button class="btn">提交</button>
    16. <script>
    17. $(".btn").click(function(){
    18. var inp1=$("#inp1").val();
    19. var inp2=$("#inp2").val();
    20. $.ajax({
    21. url:'',
    22. type:'post',
    23. dataType:'json',
    24. {#加这个就不用反序列化了,因为返回类型已经是json格式了#}
    25. data:{inp1:inp1,inp2:inp2},
    26. success:function(res){
    27. console.log(res)
    28. {#变成对象#}
    29. {#res=JSON.parse(res)#}
    30. {#后端返回的数据要反序列化,#}
    31. console.log(typeof res)
    32. console.log(res.username)
    33. console.log(res.password) // 就是拿后端返回的数据
    34. {#$("#inp3").val(res);#}
    35. {#第三个框#}
    36. }
    37. })
    38. }
    39. )
    40. </script>
    41. </body>
    42. </html>

    Ajax提交json格式的数据

    1. 浏览器请求头为:
    2. Content-Type:
    3. multipart/form-data; boundary=—-WebKitFormBoundaryA5O53SvUXJaF11O2

    views模块

    1. from django.shortcuts import render
    2. # Create your views here.
    3. import json
    4. def index(request):
    5. # # request.POST只能接收post请求的符合urlencoded编码格式的数据 {}
    6. if request.method =='POST':
    7. print(request.POST)#
    8. print(request.body)# b'{"a":1,"b":2}'
    9. json_bytes=request.body#二进制格式,接收浏览器发过来的纯原生数据,需要自己转换格式
    10. #第一种方法
    11. json_str=json_bytes.decode('utf-8') #decode 转码
    12. print(json_str)#{"a":1,"b":2}json格式
    13. json_dict=json.loads(json_str)
    14. print(json_dict)#{'a': 1, 'b': 2}字典形式
    15. #第二种方法(有bug)
    16. json_dict=json.loads(json_bytes)
    17. print((json_dict,type(json_dict)))
    18. return render(request,'index.html')

    templates\index.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    7. <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    8. <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    9. </head>
    10. <body>
    11. <button class="btn">提交</button>
    12. <script>
    13. $(".btn").click(function(){
    14. $.ajax({
    15. url:'',
    16. type:'post',
    17. data:JSON.stringify({a:1,b:2}),//序列化
    18. contentType:'application/json',//json格式的
    19. success:function(res){
    20. }
    21. })
    22. })
    23. </script>
    24. </body>
    25. </html>

     

    Ajax提交文件数据

    templates\index.html

    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>

    views

    1. from django.shortcuts import render
    2. # Create your views here.
    3. import json
    4. def index(request):
    5. if request.method =='POST':
    6. print(request.POST)#
    7. print(request.FILES)
    8. myfile=request.FILES.get('myfile')
    9. return render(request,'index.html')

  • 相关阅读:
    致远OA wpsAssistServlet 任意文件上传漏洞
    Win10配置Airsim环境并设置Python通信
    搭建完菜单后运行不显示菜单的原因及其解决方法(拼图小游戏)
    线段树——你能回答这些问题吗?(经典应用)
    基于SSM的游戏攻略网站
    SWT/ANR问题-- WiFi功能不能disable,因为进程“system_server”不能产生新的hwbinder线程
    TrustSVD算法进行基于矩阵分解的商品推荐 代码+数据(可作为毕设)
    mybatis 多对多对多 字段名一致问题解决
    QML插件的制作与应用
    写单元测试,没你想得那么简单!
  • 原文地址:https://blog.csdn.net/qq_38104453/article/details/134534298