• django组件之ajax


    AJAX简介

      AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,
    传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求; 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。 AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)
    场景:

    优点:

    1.  不用刷新整个页面
    2.  异步提交请求

    在学习ajax之前先回顾一下基本的请求形式

         客户端浏览器给服务器发请求的形式:
             
            1 地址栏输入url 回车  默认是get请求方式
            2 form表单,用户点击submit按钮  
                        --- get
                        --- post
            3 超链接标签(a标签)    默认是get请求方式
            
            4 Ajax请求
                   ---get
                   ---post
                   
                (1) 异步
                (2) 局部刷新

    基于jquery实现ajax

      在项目中存在index.html网页

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>This is index</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>  #基于jquery要先引入jquery
    </head>
    <body>
    {% csrf_token %}                                                           #中间组件csrf的影响,必须有csrf的认证
    <h3>This is index</h3>
    <button class="ajax">ajax</button>
    <p class="con"></p>
    
    <hr>
    <button class="ajax2">携参ajax</button>
    
    <hr>
    <input type="text" class="num1"> + <input type="text" class="num2"> = <input type="text" class="result"><input
            type="button" class="cal" value="计算" >
    <script>
        //ajax的简单使用
        $('.ajax').click(function () {                          #给.ajax类属性的标签绑定时间
            //发送ajax请求                       #发送ajax请求
            $.ajax({
                url:'/ajax_handle/',                            #ajax必须有的几对参数1.url 提交的路径
                type:'get',
                success:function(res){                          2. type:提交的方法 post/get
                    console.log(res);                           3.success:会执行一个函数,函数有一个参数,是来自ajax提交后的返回值
                    $('.con').html(res);                          #可以理解success是一个回调函数
                }
            })
        });
    
    //携参的ajax的使用 $('.ajax2').click(function(){                            #一样的额绑定事件,,发送请求, //发送ajax请求                                   #携参要带参数就是数据 $.ajax({                                      #data:{data里面一定要带钥匙csrf} url:'/ajax_handle2/', type:'post', data:{ a:1, b:2, csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() }, success:function (ret) { console.log(ret) } }) }); //携参实例(简单的计算器) $('.cal').click(function(){ let num1=$('.num1').val(); let num2=$('.num2').val(); console.log(num1,num2); //发送ajax请求 $.ajax({ url:'/cal/', type:'post', data:{ n1:num1, n2:num2, csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() }, success:function(res){ console.log(res); console.log(typeof res); let response=JSON.parse(res); if (response.code == "1000"){ $('.result').val(response.data) } else{ alert(response.msg) } } }) })

      视图函数

    from django.shortcuts import render,HttpResponse
    import json
    # Create your views here.
    
    def index(request):
    
    
        return render(request,'index.html')
    
    def ajax_handle(request):
    
        return HttpResponse('你好')
    
    def ajax_handle2(request):
    
        return HttpResponse('我擦嘞')
    
    def cal(request):
        response={"code":1000,"data":None,"msg":None}
        try:
            print(request.POST),
            print(request.GET),
            n1 = request.POST.get("n1")
            n2 = request.POST.get("n2")
            ret = str(int(n1) + int(n2)) #接收的是字符串,转换成数字计算完成后再转化成字符串
            response["data"]=ret
        except Exception as e :
            response["code"]=1001
            response['msg']=str(e)
        # HttpResponse只能接收字符串,用json序列化
        return HttpResponse(json.dumps(response))

       这边需要用到数据转换的语法:

    python:
      json.dumps()
      json.loads

    在JavaScript中
      JSON.stringify
      JSON.pasrse

       

      关于ajax的总结

      客户端浏览器通过执行一段Js代码向服务器发送一段ajax请求,服务器路由对应的视图函数返回一段Json字符串(建议用json)作为响应,
    浏览器接收响应后会触发该ajax请求的回调函数success,参数为响应字符串,success内通过Dom操作将结果反应到页面上,实现局部刷新,
    不像之前的请求会将响应覆盖整个页面
      
      ajax不要返回render,redirect这些响应,就只返回HttpResponse形式的Json字符串(要记得转换数据为Json)

    文件上传

    一.  在讲文件上传之前应该明确的的是无论是form表单题号还是ajax提交,其默认的内容编码格式都是 application/x-www-form-urlencoded,是没有办法发送文件的
    同时也是可以指定他们的编码格式:
    1. form:

      <form action="/put/" method="post" enctype="multipart/form-data">

    2. ajax:

      $(".ajax_btn2").click(function () {

      $.ajax({
        url:"/put1/",
        type:"post",
        contentType:"json",
        data:JSON.stringify({
            a:1,
          b:2
            }),
        success:function (res) {
          console.log(res)
          }
       })


    二. 针对post请求(有请求体)
      
    浏览器 -----------------------------> 服务器

      请求头:

      contentType:urlencoded           ----->{'name':'xxx','age':'xxx'}

      contentType:json               ---------->{}

      请求体

    就是说如果是urlencode编码格式的,django会把请求体放入字典,以字典形式的传递给服务器 ----------------->服务器可以到request.POST那数据
    如果不是urlencode编码格式的,django就不会帮你封装 ---------------------------->,reuqest.POST是个空字典,服务器只能到request.body拿数据


    基于表单form的文件上传

      页面中:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h3>form表单上传</h3>
    <form action="/put/" method="post" enctype="multipart/form-data">  #必须设置为enctype="multipart/form-data"否则服务端只能拿到文件名
    {% csrf_token %}
    <input type="text" name="user">
    <input type="file" name="file">
    <input type='submit'> #看清楚了,这边的提交按钮是input标签
    </form>

    </body>
    </html>

      在视图函数中:

    from django.shortcuts import render,HttpResponse
    import os
    # Create your views here.
    def index(request):
    
        return render(request,'index.html')
    
    def put(request):
        print(request.POST)
        print(request.FILES)
        file_obj=request.FILES.get('file')  #获得文件句柄
        # path=file_obj.name
        name=file_obj.name
        with open(os.path.join('media','imgs',name),'wb') as f:  #把拿到的文件句柄循环一行一行的写入文件中
            for line in file_obj:
                f.write(line)
        return HttpResponse('上床成功')

    基于ajax文件上传

     index.html中

    <h>ajax文件上传</h>
    <form>                                  #这边的form标签只是为了把内容包起来,用div也可以
        <input type="text" class="user">
        <input type="file" class="file">
        <input type="button" class="ajax_btn2" value="ajax上传">
    </form>

    视图函数中

    <script>
        {#ajax文件上传  #}
        $('.ajax_btn2').click(function () {
            let formdata=new FormData();
            formdata.append("user",$('.user').val());
            formdata.append('file',$(".file")[0].files[0]);
            $.ajax({
                url:'/put/',
                type:'post',
                contentType:false,                  #这两个参数必须设置,否则也不能把文件上传
                processData:false,
                data:formdata,
                success:function (res) {
                    console.log(res)
                },
            })
    
        })
    </script>
    
    
  • 相关阅读:
    Leetcode Reverse Words in a String
    topcoder SRM 619 DIV2 GoodCompanyDivTwo
    topcoder SRM 618 DIV2 MovingRooksDiv2
    topcoder SRM 618 DIV2 WritingWords
    topcoder SRM 618 DIV2 LongWordsDiv2
    Zepto Code Rush 2014 A. Feed with Candy
    Zepto Code Rush 2014 B
    Codeforces Round #245 (Div. 2) B
    Codeforces Round #245 (Div. 2) A
    Codeforces Round #247 (Div. 2) B
  • 原文地址:https://www.cnblogs.com/tjp40922/p/10244423.html
Copyright © 2020-2023  润新知