django ajax application

ajax:

  1. What is ajax, what role:

    Before we submit the data to the back of the page are using from the form, this will be submitted to refresh the entire page all at the time of submission, after the discovery of a data if you do not submit when filling out the form, but you submitted this page will be refreshed, you want to change can only start over, so the user experience is not good sense; so there is ajax, it can help developers solve this problem;

     AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步的Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。
     # 特点:异步请求和局部刷新  
    1. 局部刷新: 即不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
    2. AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。
          a.同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
          b.异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
  2. ajax applications:

    {% load static %}      # 导入文件路径,固定写法不能更改
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    </head>
    <body>
    
    <div class="container" style="width: 500px;">
      <div class="form-group">
        <label  class="col-sm-2 control-label">账号</label>
        <div class="col-sm-10">
          <input type="text" class="form-control"  placeholder="账号" name="account" id="name">
        </div>
      </div>
      <div class="form-group">
        <label  class="col-sm-2 control-label">密码</label>
        <div class="col-sm-10">
          <input type="password" class="form-control"  placeholder="密码" name="password" id="pwd">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" id="but">提交</button>
            <span id="error"></span>
        </div>
      </div>
    </div>
    </body>
    <script src="{% static 'jquery.js' %}"></script>   
       # 导入本地的文件时直接写一个static后边加加上文件名就行
    <script>
         # 触发器,当你鼠标点击提交按钮时触发,执行下边的代码
        $('#but').click(function () {    
             # 获取输入框需要提交到后台的数据
            var account = $('#name').val();   
            var password = $('#pwd').val();    
            # 下边就是ajax的写法,
            # 通过ajax将拿到的数据发送给后端
            $.ajax({
                # 下边是发送请求的路径,
                url:'{% url 'login' %}',     # login是urls.py文件中相关路径别名
                # 发送请求的类型,post请求
                type:'post',
                # 下边是你需要提交到后端的数据,写成一个字典形式
                data:{account:account,password:password},
                # 下边是一个响应函数 ret是从后端返回的数据
                success:function (ret) {
                    if (ret === '1'){ # 对后端返回的值进行比较是不是相同
                    # 判断成功后使用location方法将当前页面跳转到指定的页面/home/
                        location.href='/home/'
                    }
                    else{
                        $('#error').text('用户名或者密码错误!')
                    }
                }
            })
        })
    </script>
    </html>
  3. How do the back-end processing and receiving data:

    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
     # 从ajax返回的数据是一个字典的形式,所以直接可以get去相应的值
        name = request.POST.get('name')
        pwd = request.POST.get('password')
     # 对相应的数据进行比较
        if name == 'adrian' and pwd == '123':
            # 成功之后返回一个值
            return HttpResponse('1') 
        # 失败之后返回一个值
        return HttpResponse('0')
  4. csrftoken

    DETAILED DESCRIPTION CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also called: one click attack / session riding, abbreviated: CSRF / XSRF. Jiang attacker via HTTP request data to the server, so the answer to steal cookie. After the answer to steal cookie, an attacker can not only get information about the user, you can also modify the account information associated with the cookie.

      img

      So to solve the most direct way csrf attack is to generate a random csrftoken value stored on the user's page, every request with a value over complete verification.

  5. ajax had csrf certification

    方式1:# 这个方式是将{% csrf_token %}写在前端的页面中,
        $.ajax({
          url: "/cookie_ajax/",
          type: "POST",
          data: {
            "username": "chao",
            "password": 123456,
            "csrfmiddlewaretoken": $("[name = 'csrfmiddlewaretoken']").val()  
              # 使用jQuery从页面中取出csrfmiddlewaretoken的值,拼接到data中
          },
          success: function (data) {
            console.log(data);
          }
        })
    
    方式2:# 写在ajax中在服务器向浏览器发送页面的时候进行模板渲染的时候就进行替换了
     $.ajax({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
        });
    方式3
     #这个方式是使用jquery来操作cookie值:
        首先需要导入一个文件包:这个包是专门用来操作cookie的 下载网址 https://plugins.jquery.com/cookie/
        <script type="text/javascript" src="js/jquery.cookie.js"></script>
     $.ajax({
    
         headers:{"X-CSRFToken":$.cookie('csrftoken')},    
            #其实在ajax里面还有一个参数是headers,自定制请求头,可以将csrf_token加在这里,我们发contenttype类型数据的时候,csrf_token就可以这样加
    
    })
    
    jquery操作cookie: https://www.cnblogs.com/clschao/articles/10480029.html

form file upload form:

  1. Note that: enctype

    <form action="" method="post" enctype="multipart/form-data">  
    # 注意如果用form表单上传文件时,需要设置上传的格式  enctype="multipart/form-data"  这种form_data的格式一般是把大数据一段一段隔开的
        {% csrf_token %}
        用户名: <input type="text" name="username">
        密码: <input type="password" name="password">
        头像: <input type="file" name="file"> # 获取文件
        <input type="submit">
    </form>
    
    
    views.py
    def upload(request):
        if request.method == 'GET':
            print(settings.BASE_DIR) #/static/
            return render(request,'upload.html')
        else:
            print(request.POST)
            print(request.FILES)
            uname = request.POST.get('username')
            pwd = request.POST.get('password')
            file_obj = request.FILES.get('file')  #文件对象
            print(file_obj.name) # 获取文件名称
            with open(file_obj.name,'wb') as f:
                # for i in file_obj:
                #     f.write(i)
                for chunk in file_obj.chunks():
                    f.write(chunk)
            return HttpResponse('ok')

ajax file upload:

  1. parameter:

    1. processData:声明当前的data数据是否进行转码或预处理,默认为true,即预处理;if为false,
                 那么对data:{a:1,b:2}会调用json对象的toString()方法,即{a:1,b:2}.toString()
                 ,最后得到一个[object,Object]形式的结果。
    
    2. contentType:默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。
                 用来指明当前请求的数据编码格式;urlencoded:?a=1&b=2;如果想以其他方式提交数据,
                 比如contentType:"application/json",即向服务器发送一个json字符串:
                   $.ajax("/ajax_get",{
                      data:JSON.stringify({
                           a:22,
                           b:33
                       }),
                       contentType:"application/json",
                       type:"POST",
                   });                          //{a: 22, b: 33}
                 注意:contentType:"application/json"一旦设定,data必须是json字符串,不能是json对象
                 views.py:   json.loads(request.body.decode("utf8"))
    
    3. traditional:一般是我们的data数据有数组时会用到 :data:{a:22,b:33,c:["x","y"]},
                  traditional为false会对数据进行深层次迭代;  
  2. operating:

    $('#but').click(function () {
    
            var formdata = new FormData();
            {#由于ajax不能像form表单那样设置上传文件的格式,所以就需要借助FormData#}
            {# 首先创建一个formdata对象#}
            var files = $('[type=file]')[0].files[0];
         {#首先需要获取到文件信息,需要使用DOM的方法files来获取#}
            formdata.append('file',files);
            {#将需要的文件添加到这个对象中#}
    
            $.ajax({
                url:'{% url 'input' %}',
                type:'post',
                data:formdata,
                {#上传数据时直接写这个对象就行#}
                processData:false,   {#不处理数据#}
                contentType:false,   {#不设置内容类型#}
                headers:{"X-CSRFToken":$.cookie('csrftoken')},
                success:function (ret) {
                 {#逻辑代码#}
                }
            })
        })
    

Guess you like

Origin www.cnblogs.com/zhufanyu/p/11666611.html