Django ajax 簡單介紹

AJAX

Asynchronous Javascript And XML是 "異步Javascript和XML"。即便用 Javascript 語言與服務器進行異步交互,傳輸的數據爲XML。html

同步交互:客戶端發出一個請求後,須要等待服務器響應結束後,才能發出第二個請求;
異步交互:客戶端發出一個請求後,無需等待服務器響應結束,就能夠發出第二個請求。ajax

優勢:
AJAX使用Javascript技術向服務器發送異步請求;
AJAX無須刷新整個頁面;
由於服務器響應內容再也不是整個頁面,而是頁面中的局部,因此AJAX性能高;
缺點:
AJAX並不適合全部場景,不少時候仍是要使用同步交互;
AJAX雖然提升了用戶體驗,但無形中向服務器發送的請求次數增多了,致使服務器壓力增大;
由於AJAX是在瀏覽器中使用Javascript技術完成的,因此還須要處理瀏覽器兼容性問題;django

大概步驟:
step 1: var xmlhttp=XMLHttperquest()
step 2: xmlhttp.open("")
step 3: xmlhttp.send("name=klvchen") # 請求體的內容若是爲 GET 請求則爲 send(null)
step 4: if(xmlhttp.readyState===4 && xmlhttp.status===200) # 監聽瀏覽器


ajax 發送GET請求

建立一個 Ajax_lesson 項目 和 app01 應用
修改 urls.py 文件服務器

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('ajax_receive/', views.ajax_receive),
]

在 tempates 文件夾中添加 index.html 文件app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="func1()">ajax提交</button>
</body>

<script>
    function createXMLHttpRequest() {
            var xmlHttp;
            try{
                xmlHttp = new XMLHttpRequest();
            } catch (e) {
                try {
                    // 適用於IE6
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }catch (e) {
                    try {
                        // 適用於IE5.5,以及IE更早版本
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch (e) {

                    }
                }

            }

            return xmlHttp;
        }

    function func1() {
        var xmlhttp = createXMLHttpRequest()
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var data = xmlhttp.responseText;
                alert(data);
            }
        }
        xmlhttp.open("GET", "/ajax_receive/", true);
        xmlhttp.send(null);

    }


</script>
</html>

在 views.py 上修改less

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax_receive(request):
    print('ok')
    return HttpResponse("hello world2")


ajax 發送POST請求

修改 index.html 文件異步

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="func1()">ajax提交</button>
</body>

<script>
    function createXMLHttpRequest() {
            var xmlHttp;
            try{
                xmlHttp = new XMLHttpRequest();
            } catch (e) {
                try {
                    // 適用於IE6
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                }catch (e) {
                    try {
                        // 適用於IE5.5,以及IE更早版本
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch (e) {

                    }
                }

            }

            return xmlHttp;
        }

    function func1() {
        var xmlhttp = createXMLHttpRequest()

        xmlhttp.open("POST", "/ajax_receive/", true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       
        xmlhttp.send("name=klvchen");

        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var data = xmlhttp.responseText;
                alert(data);
            }
        }

    }


</script>
</html>

修改 views.py 文件post

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax_receive(request):
    if request.method=="POST":
        print("req.POST", request.POST)
    return HttpResponse("hello world2")

在 settings.py 文件中註釋性能

#'django.middleware.csrf.CsrfViewMiddleware',


相關文章
相關標籤/搜索