Django 學習筆記(五) --- Ajax 傳輸數據

人生苦短 ~ javascript

Tips:僅適用於 Python 3+(反正差異不大,py2 改改也能用)。由於據 Python 之父 Guido van Rossum 說會在 2020 年中止對 Python 2 的官方支持,因此若是你還在使用 Python 2 那就要早作準備了,畢竟沒有官方的支持使用起來也不順心的。html

 

1. Ajax 介紹java

Ajax 即 「A synchronous J avascript And X ML」(異步 JavaScript 和 XML),是指一種建立交互式網頁應用的網頁開發技術。
Ajax = 異步 J avascript 和 X ML(標準通用語言的子集)。
Ajax 是一種用於建立快速動態網頁的技術。
Ajax 是一種在無需從新加載整個網頁的狀況下,可以更新部分網頁的技術。
經過在後臺與服務器進行少許數據交換,Ajax 可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。
傳統的網頁(不使用 Ajax)若是須要更新內容,必須重載整個網頁頁面。
 
來源:百度百科

 

2. 視圖頁面jquery

 在文件夾 \templates 中新建頁面 ajax_request.html 和在 /static/js/ajax_request.js 頁面,html 文件暫時添加以下代碼,js 文件暫時爲空:ajax

<!DOCTYPE html>
{% load static %} <!-- 模板標籤加載靜態文件路徑,也能夠改爲 load staticfiles -->
<html>
<head>
    <title>HelloDjango</title>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script><!-- 這裏引入的是百度的 JQuery -->
    <script type="text/javascript" src="{% static 'js/ajax_request.js' %}"></script> <!-- 咱們 get post 請求須要使用的自定義 js -->
</head>
<body>
    
</body>
</html>

在咱們的應用模塊中 /mydjango/views.py 添加如下四個函數,函數暫時返回空:django

# 默認訪問頁面
def ajax_index(request):
    return render(request, 'ajax_request.html')
    
# Ajax GET 提交數據
def ajax_get(request):
    return HttpResponse('')
    
# Ajax POST 提交數據
def ajax_post(request):
    return HttpResponse('')
    
# Ajax 返回 JSON 數據
def ajax_json(request):
    return HttpResponse('')

在咱們的應用模塊中 /mydjango/urls.py 添加一下四個訪問連接:json

path('ajax/index/', views.ajax_index),
path('ajax/get/', views.ajax_get),
path('ajax/post/', views.ajax_post),
path('ajax/json/', views.ajax_json),

 

3. GET 提交數據瀏覽器

在 ajax_request.html 頁面 body 中添加須要提交數據的 html 代碼:服務器

    <h3>GET 提交數據:</h3>
    <input type="number" id="num1" />&nbsp;*&nbsp;
    <input type="number" id="num2" />
    <button onclick="fun_get();">&nbsp;=&nbsp;</button>
    <font style="color:red;"><span id="result_get"></span></font>
    <hr />

在 views.py 中的 ajax_get 方法中獲取數據並實現操做:app

# Ajax GET 提交數據
def ajax_get(request):
    a = request.GET.get("a")
    b = request.GET.get("b")
    n = int(a) * int(b)
    return HttpResponse(str(n))

js 添加 get 請求操做:

function fun_get() {
    var a = $("#num1").val();
    var b = $("#num2").val();
    $.get("/mydjango/ajax/get/", { 'a': a, 'b': b }, function(ret){
        $('#result_get').html(ret);
    });
}

能夠看到瀏覽器請求的地址和執行結果:

 

4. POST 提交數據

在 ajax_request.html 頁面 body 中添加須要提交數據的 html 代碼:

    <h3>POST 提交數據:</h3>
    <input type="number" id="num_post1" />&nbsp;*&nbsp;
    <input type="number" id="num_post2" />
    <button onclick="fun_post();">&nbsp;=&nbsp;</button>
    <font style="color:red;"><span id="result_post"></span></font>
    <hr />

在 views.py 中的 ajax_post 方法中獲取數據並實現操做:

# Ajax POST 提交數據,csrf_exempt 是告訴你的視圖不要檢查 csrf 標記,不加的話會報 403 錯誤
# 須要導入包 from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def ajax_post(request):
    a = request.POST.get("a", 0) # 0 是默認值
    b = request.POST.get("b", 0)
    n = int(a) * int(b)
    return HttpResponse(str(n))

js 添加 post 請求操做:

function fun_post() {
    var a = $("#num_post1").val();
    var b = $("#num_post2").val();
    $.ajax({
        type : 'post',
        url : '/mydjango/ajax/post/',
        dataType : 'json',
        data : {
            'a': a,
            'b': b
        },
        success : function(ret) {
            $('#result_post').html(ret);
        },
        error : function(err) {
        }
    });
}

能夠看到瀏覽器請求的地址和執行結果:

 

5. POST 返回 JSON 數據

在 ajax_request.html 頁面 body 中添加須要提交數據的 html 代碼:

    <h3>POST 請求 JSON 數據:</h3>
    <button onclick="fun_json();">&nbsp;請求 JSON&nbsp;</button>
    <font style="color:green;"><span id="result_json"></span></font>
    <hr />

在 views.py 中的 ajax_json 方法中獲取數據並實現操做:

# Ajax 返回 JSON 數據,csrf_exempt 是告訴你的視圖不要檢查 csrf 標記,不加的話會報 403 錯誤
# 須要導入包 from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def ajax_json(request):
    name_dict = {'name': 'Django', 'age': 18, 'phone': '13500000000'}
    return HttpResponse(json.dumps(name_dict), content_type='application/json')

js 添加 post 請求 JSON 操做:

function fun_json() {
    $.ajax({
        type : 'post',
        url : '/mydjango/ajax/json/',
        dataType : 'json',
        success : function(ret) {
            $('#result_json').html(JSON.stringify(ret));
        },
        error : function(err) {
        }
    });
}

能夠看到瀏覽器請求的地址和執行結果:

 

~ 我學 Python

相關文章
相關標籤/搜索