AJAX small sample

First, the basic content

  1. Definitions: AJAX (Asynchronous Javascript And XML) translated into Chinese is "asynchronous Javascript and XML", that the use of Javascript language to interact with the server asynchronous data transmission for XML (Of course, data transmission is not just XML)

  2. Action: AJAX techniques js is the use of a transmission request and receiving the response

  3. Pros: without reloading the entire page, you can exchange data with the server and update parts of the page content

  4. Features:

    • Asynchronous interaction
      • Synchronous interaction: The client makes a request, the server needs to wait for the end of the response, in order to issue a second request
      • Asynchronous Interaction: the client sends a request to the server without waiting for the end of the response, it can issue a second request
    • Partial refresh without refreshing the entire page
    • A small amount of data transmission, high-performance
  5. Scenario:

    • Search engines based on keywords entered by the user, automatically prompts a search keyword
    • Re-check the user name registration time
  6. Common examples: page input two integers, to calculate a rear end and returns the result transmitted through AJAX

    # urls.py
    urlpatterns = [
        url(r'^ajax_add/', views.ajax_add),
        url(r'^ajax_demo1/', views.ajax_demo1),  
    ]
    # views.py
    def ajax_demo1(request):
        return render(request, "ajax_demo1.html")
    
    def ajax_add(request):
        i1 = int(request.GET.get("i1"))
        i2 = int(request.GET.get("i2"))
        ret = i1 + i2
        return JsonResponse(ret, safe=False)
    {# ajax_demo1.html #}
    <input type="text" id="i1">+
    <input type="text" id="i2">=
    <input type="text" id="i3">
    <input type="button" value="AJAX提交" id="b1">
    
    <script src="/static/jquery-3.2.1.min.js"></script>
    <script>
        $("#b1").on("click", function () {
            $.ajax({
                url:"/ajax_add/",
                type:"GET",
                data:{"i1":$("#i1").val(),"i2":$("#i2").val()},
                success:function (data) {
                    $("#i3").val(data);
                },
                error:function (error) {
                    console.log(error)
                },
            })
        })
    </script>

Two, jQuery AJAX implementation

  • The most basic example jQuery AJAX request transmission

    # views.py
    def ajax_test(request):
        user_name = request.POST.get("username")
        password = request.POST.get("password")
        print(user_name, password)
        return HttpResponse("OK")
    <button id="ajaxTest">AJAX 测试</button>
    <script>
        $("#ajaxTest").click(function () {
            $.ajax({
                url: "/ajax_test/",
                type: "POST",
                data: {username: "Q1mi", password: 123456},
                success: function (data) {
                    alert(data)
                }
            })
        })
    </script>
  • $ .Ajax parameters

    • key-value pairs of data parameter, if the value is not a string, it is necessary to convert it to a string type

      <script>
          $("#b1").on("click", function () {
              $.ajax({
                  url:"/ajax_add/",
                  type:"GET",
                  data:{"i1":$("#i1").val(),"i2":$("#i2").val(),"hehe": JSON.stringify([1, 2, 3])},
                  success:function (data) {
                      $("#i3").val(data);
                  }
              })
          })
      </script>

Three, AJAX by checking the csrf

  1. Prerequisites: Ensure that the cookie csrftoken

    • Use {% csrf_token%} in the page
    • Plus decorator: ensure_csrf_cookie
    • note:
      • If you use csrftoken taken from the cookie, the cookie needs to ensure that there is value csrftoken
      • If you view the rendered HTML file does not contain {% csrf_token%}, Django might not have set CSRFtoken the cookie.
      • This time need to use ensure_csrf_cookie () Cookie forcibly set decorator
  2. AJAX request How to set csrf_token

    • Csrfmiddlewaretoken by obtaining the value of a hidden input tag, the transmission data is placed in the
    $.ajax({
     url: "/cookie_ajax/",
     type: "POST",
     data: {
         "username": "Q1mi",
         "password": 123456,
         {# 使用jQuery取出csrfmiddlewaretoken的值,拼接到data中 #}
         "csrfmiddlewaretoken": $("[name = 'csrfmiddlewaretoken']").val()
     },
     success: function (data) {
         console.log(data);
     }
    })
    • By obtaining the returned cookie string is placed in the request header transmitted
      • Note: The need to introduce a plug-jquery.cookie.js
    $.ajax({
     url: "/cookie_ajax/",
     type: "POST",
     {# 从Cookie取csrftoken,并设置到请求头中 #}
     headers: {"X-CSRFToken": $("[name = 'csrfmiddlewaretoken']").val()},
     data: {"username": "Q1mi", "password": 123456},
     success: function (data) {
         console.log(data);
     }
    })
    • Use file: to write a method getCookie
      • Paste in the static of a js file js in, such as: ajax_setup.js
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    // 通过js获取csrftoken的值
    var csrftoken = getCookie('csrftoken');
    
    // 使用$.ajaxSetup()方法为ajax请求统一设置
    function csrfSafeMethod(method) {
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    
    $.ajaxSetup({
      beforeSend: function (xhr, settings) {
        // 不是 GET|HEAD|OPTIONS|TRACE 这些请求的话,就执行if后的操作
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);   // 设置请求头,本质同方法2
        }
      }
    });

Four, AJAX upload files

  • Upload file example

    <input type="file" id="f1">
    <button id="b1">上传</button>
    
    <script src="/static/jquery.js"></script>
    <script>
        $('#b1').click(function () {
            var  formobj =  new FormData();
            formobj.append('file',$('#f1')[0].files[0]);
            formobj.append('name','alex');
            $.ajax({
                url: '/upload/',
                type: 'post',
                data:formobj ,
                processData:false,
                contentType:false,
                success: function (res) {
                    $("[name='i3']").val(res)
                },
            })
        })
    </script>

Guess you like

Origin www.cnblogs.com/zengyi1995/p/11291417.html