一個簡單加法的例子
網上找了些資料,大部分資料由于Django版本低,沒法直接用,自己寫好做個記錄。
做ajax頁面請求主要有 點:
urls.py
建立兩個url路徑,demo_ajax
和demo_add
:
urlpatterns = [
…………
path('demo_ajax/', hc_views.demo_ajax),
path('demo_add/', hc_views.demo_add),
]
demo_ajax
顯示加法輸入框和按鈕,demo_add
導航到views
試圖,用于處理加法并返回結果。
views.py
兩個試圖對應兩個urls,demo_ajax
視圖直接渲染demo_ajax.html
模板,demo_add
視圖處理GET
請求。
def demo_ajax(request):
return render(request, 'demo_ajax.html')
def demo_add(request):
a=request.GET['a']
b=request.GET['b']
if request.is_ajax():
ajax_string = 'ajax request: '
else:
ajax_string = 'not ajax request: '
c = int(a) + int(b)
r = HttpResponse(ajax_string + str(c))
return r
HTML模板頁面
<!DOCTYPE html>
<html>
<head>
{% load static %}
</head>
<body>
<p>請輸入兩個數字</p>
<form action="/demo_add/" method="get">
a: <input type="text" id="a" name="a"> <br>
b: <input type="text" id="b" name="b"> <br>
<p>result: <span id='result'></span></p>
<button type="button" id='sum'>提交</button>
</form>
<script src="{% static 'jquery/jquery.js' %}"></script>
<script>
//這里是關鍵點 .ready 函數好像監聽器。
$(document).ready(function () {
//jq的處理函數,當點擊提交按鈕時執行。
$("#sum").click(function () {
//得到頁面中id為a和b兩個標簽的值
var a = $("#a").val();
var b = $("#b").val();
//向服務器發送get請求,請求地址為demo_add
$.get("/demo_add/", { 'a': a, 'b': b }, function (ret) {
//請求結果為ret,將請求結果賦值給id為result的節點
$('#result').html(ret)
})
});
});
</script>
</body>
</html>
結果
image.png