index.html:javascript
<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:html
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/java
輸入兩組數,點擊提交python
這裏須要驗證 csrf tokenjquery
在 index.html 中添加 csrf tokenajax
訪問,http://127.0.0.1:8000/index/django
右鍵 -> 檢查cookie
取到 nameui
修改 index.html:this
{% 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>
運行結果: