Python - Django - AJAX 實現 POST 請求


index.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.3.1.js"></script>
<script>
    $("#b1").on("click", function () {
        $.ajax({
            url: "/ajax_add/",
            type: "POST",
            data: {"i1": $("#i1").val(), "i2": $("#i2").val()},
            success: function (data) {
                $("#i3").val(data);
            }
        })
    });
</script>

views.py:

from django.shortcuts import render, HttpResponse


def index(request):
    return render(request, "index.html")


def ajax_add(request):
    num1 = request.POST.get("i1")
    num2 = request.POST.get("i2")
    ret = int(num1) + int(num2)
    return HttpResponse(ret)

訪問,http://127.0.0.1:8000/index/

 

輸入兩組數,點擊提交

 

這里需要驗證 csrf token

 

方法一:

在 index.html 中添加 csrf token

 

訪問,http://127.0.0.1:8000/index/

右鍵 -> 檢查

 

取到 name

修改 index.html:

{% csrf_token %}
<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.3.1.js"></script>
<script>
    $("#b1").on("click", function () {
        var csrfToken = $("[name='csrfmiddlewaretoken']").val();
        $.ajax({
            url: "/ajax_add/",
            type: "POST",
            data: {"i1": $("#i1").val(), "i2": $("#i2").val(), "csrfmiddlewaretoken": csrfToken},
            success: function (data) {
                $("#i3").val(data);
            }
        })
    });
</script>

運行

 

 

方法二:

在 /static/ 目錄下創建 test.js:

// 獲取 cookie
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]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');  // 獲取 cookie 中的 csrf token

// 哪些請求方法不需要用到 csrf token
function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

// 要用到 csrf token
$.ajaxSetup({
  beforeSend: function (xhr, settings) {  // 在發送請求之前
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);  // 在請求頭中添加 csrf token
    }
  }
});

在 index.html 中導入該 js 文件

{% csrf_token %}
<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.3.1.js"></script>
<script src="/static/test.js"></script>
<script>
    $("#b1").on("click", function () {
        $.ajax({
            url: "/ajax_add/",
            type: "POST",
            data: {"i1": $("#i1").val(), "i2": $("#i2").val()},
            success: function (data) {
                $("#i3").val(data);
            }
        })
    });
</script>

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM