Django(十二)視圖--利用jquery從后台發送ajax請求並處理、ajax登錄案例


一、Ajax基本概念

【參考】:https://www.runoob.com/jquery/jquery-ajax-intro.html
異步的javascript。在不全部加載某一個頁面部的情況下,對頁面進行局的刷新,ajax請求都在后台。
圖片,css文件,js文件都是靜態文件。

1.1ajax基本用法

$.ajax({
'url':請求地址,
'type':請求方式,
'dataType':預期返回的數據格式
'data':參數
}).success(function(data){
//回調函數(data即返回的數據)
})

1.2完整過程示意

  1. 發起ajax請求:jquery發起
  2. 執行相應的視圖函數,返回json內容
  3. 執行相應的回調函數。通過判斷json內容,進行相應處理。
    在這里插入圖片描述

二、Ajax登錄案例

2.1ajax測試案例

第1步,下載 jquery:https://jquery.com/download/

下載第2個開發,未壓縮版本 https://code.jquery.com/jquery-3.4.1.js
【1】compressed, production jQuery 3.4.1- 用於實際的網站中,已被精簡和壓縮。
【2】uncompressed, development jQuery 3.4.1 - 用於測試和開發(未壓縮,是可讀的代碼)

第2步,部署jquery,在根目錄下建立 /static/js、css、images、

  1. 把jquery.js文件放入js文件夾

第3步,設置project1/settings.py,拉到最底下:

設置靜態文件的保存目錄

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # 設置靜態文件的保存目錄

第4步,創建ajax請求示例頁面templates/app1/test_ajax.html,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        $(function () {
        
            // 綁定btnAjax的click事件
            $('#btnAjax').click(function () {
                alert(1)
                $.ajax({
                    'url': '/ajax_handle',
                    'dataType': 'json',
                    // 'async': false, // 同步的ajax請求
                }).success(function (data) {
                    // 進行處理
                    alert(2)
                    if (data.res == 1){
                        $('#message').show().html('提示信息')
                    }
                })
                alert(3)
            })

        })
    </script>
    <style>
        #message {
            display: none;
            color: red;
        }
    </style>
</head>
<body>
<input type="button" id="btnAjax" value="ajax請求">
<div id="message"></div>
</body>
</html>

第5步,配置app1/urls.py

path(r'test_ajax',views.test_ajax),#ajax測試頁
path(r'ajax_handle/',views.ajax_handle),#ajax處理頁

第6步,編寫app1/views.py

  1. 引入json模塊
  2. ajax測試頁面
  3. ajax請求處理
from django.shortcuts import render,redirect #引入重定向簡寫模塊
from app1.models import BookInfo,AreaInfo #從模型下導入bookinfo數據模型
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse #引入返回請求模塊、重新定向模塊、json模塊
from datetime import date # 引用時間模塊

# /test_ajax
def test_ajax(request):
    '''顯示ajax頁面'''
    return render(request, 'app1/test_ajax.html')

def ajax_handle(request):
    '''接收ajax請求處理,返回json數據'''
    # 返回的json數據 {'res':1}
    return JsonResponse({'res':1})

效果:http://127.0.0.1:8000/test_ajax

點擊按鈕后,用jquery發起ajax請求,服務器返回請求,jquery處理返回數據,在頁面顯示出來提示信息,但頁面並未整體刷新:
在這里插入圖片描述
后台的ajax請求查看:
在這里插入圖片描述

技巧:出錯調試也在調試里的network里查看

在這里插入圖片描述

2.2 ajax的異步和同步請求控制(上步的4步)

還是在templates/app1/test_ajax.html把js部分加上alert(1),2,3查看運行順序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        $(function () {

            // 綁定btnAjax的click事件
            $('#btnAjax').click(function () {
                alert(1)//【1】
                $.ajax({
                    'url': '/ajax_handle',
                    'dataType': 'json',
                    // 'async': false, // 【4】同步的ajax請求
                }).success(function (data) {
                    // 進行處理
                    alert(2)//【2】
                    if (data.res == 1){
                        $('#message').show().html('提示信息')
                    }
                })
                alert(3)//【3】
            })

        })
    </script>
    <style>
        #message {
            display: none;
            color: red;
        }
    </style>
</head>
<body>
<input type="button" id="btnAjax" value="ajax請求">
<div id="message"></div>
</body>
</html>

效果:運行發現運行順序為1,3,2,而不是預期的1,2,3這即是異步

把第【4】項注釋取消,順序即變成1,2,3,又變回同步

同步設置:'async': false,

<script>
        $(function () {

            // 綁定btnAjax的click事件
            $('#btnAjax').click(function () {
                alert(1)//【1】
                $.ajax({
                    'url': '/ajax_handle',
                    'dataType': 'json',
                    'async': false, // 【4】同步的ajax請求
                }).success(function (data) {
                    // 進行處理
                    alert(2)//【2】
                    if (data.res == 1){
                        $('#message').show().html('提示信息')
                    }
                })
                alert(3)//【3】
            })

        })
    </script>

2.3 ajax登錄案例

【目標】:實現用戶信息輸入錯誤,也不刷新頁面清空數據,直接提示錯誤,省得再次輸入信息

1) 首先,分析出請求地址時需要攜帶的參數。

  1. 視圖函數處理完成之后,所返回的json的格式。
  2. 顯示出登錄頁面:
    a) 設計url,通過瀏覽器訪問 http://127.0.0.1:8000/login_ajax 時顯示登錄頁面。
    b) 設計url對應的視圖函數login_ajax。
    c) 編寫模板文件login_ajax.html:在里面寫jquery代碼發起ajax請求。

2) 然后,登錄校驗功能

a) 設計url,點擊登錄頁的登錄按鈕發起請求http://127.0.0.1:8000/login_ajax_check時進行登錄校驗。
b) 設計url對應的視圖函數login_ajax_check:

  1. 接收post提交過來的數據。
  2. 進行登錄校驗,並返回json內容。 JsonRepsone
  3. Json格式如下:
{'res':'1'} #表示登錄成功
{'res':'0'} #表示登錄失敗

第1步,templates/app1/login.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <!-- 【0】引入jquery -->
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <title>登錄頁面</title>
</head>
<script>
    // 【5】寫ajax處理函數
    $(function () {
        $('#btnLogin').click(function () {
            //1.獲取用戶名、密碼
            username=$('#username').val()
            password=$('#password').val()
            //2.發起ajax--post(username,password)請求驗證,地址:/login_check
            $.ajax({
                'url':'/login_check',//驗證地址
                'type':'post',//請求類型
                'data':{'username':username,'password':password},//發送數據
                'dataType':'json',//希望返回數據類型
            }).success(function(data){
                //成功返回{'res':1},失敗{'res':0}
                if(data.res===0){
                    $('#msg').show().html('用戶名或密碼錯誤請重試!')//登錄失敗則顯示msg,並在里寫入信息
                }else{//成功跳轉到books頁面
                    location.href='/books'
                }
            })

        })
    })
</script>
<style>
    /* 【4】信息提示樣式 */
#msg{
    display: none;
    color:red;
}
</style>
<body>
    <!-- 【1】原form刪除,input的name變id,方便jquery操作 -->
    用戶名:<input type="text" id="username"><br/>
    密碼:<input type="password" id="password"><br/>
    <!-- 【2】加入一個信息提示框,用於密碼等錯誤提示 -->
    <div id="msg"></div>
    <!-- 【3】按鈕type改button,加一個id方便jquery操作 -->
    <input type="button" id="btnLogin" value="登錄">

</body>
</html>

第2步,app1/views.py處理函數

  1. 登錄頁函數
  2. 登錄校驗函數
from django.shortcuts import render,redirect #引入重定向簡寫模塊
from app1.models import BookInfo,AreaInfo #從模型下導入bookinfo數據模型
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse #引入返回請求模塊、重新定向模塊
from datetime import date # 引用時間模塊

def login(request):
    '''登錄頁'''
    return render(request,'app1/login.html')

def login_check(request):
    '''登錄校驗'''
    #1.獲取用戶名密碼
    username=request.POST.get('username')
    password=request.POST.get('password')
    #2.進行校驗,並返回json數據
    if username=='jim' and password=='123':
        #return redirect('/books')
        return JsonResponse({'res':1}) #正確返回1
    else:
        #return redirect('/login')
        return JsonResponse({'res':0}) #錯誤返回0

第3步,app1/ulrs.py配置

    path('login/',views.login),#登錄頁
    path('login_check',views.login_check),#登錄檢測

效果:http://127.0.0.1:8000/login/

不正確:則在不刷新頁面情況下提示錯誤信息(用於名,密碼都還在,不要再次填寫),
正確:則跳轉到頁面 http://127.0.0.1:8000/books
在這里插入圖片描述

注意:settings.py別忘記設置

設置靜態文件的保存目錄

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # 設置靜態文件的保存目錄


免責聲明!

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



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