1. 程式人生 > >AJAX入門學習-2:基於JS的AJAX實現(以Django為例)

AJAX入門學習-2:基於JS的AJAX實現(以Django為例)

data from 博客 password als ont 提交數據 open type

小生博客:http://xsboke.blog.51cto.com

如果有疑問,請點擊此處,然後發表評論交流,作者會及時回復。

                        -------謝謝您的參考,如有疑問,歡迎交流

一. ajax的實現操作流程

        實例對象:
                var xmlhttp = XMLHttprequest() 

        連接server端:
                xmlhttp.open("")

        發送數據:
                xmlhttp.send("")        # 請求體的內容    ,如果是GET請求就沒有內容,內容在URL裏面,寫為send(null)

        監聽:
                xmlhttp(if == 4:{var context = xmlhttp.responsetext})  # 判斷服務器是否響應結束,其中4狀態表示服務器響應結束

二. ajax第一樣例,發送get請求

2.1 django的urls.py

        from django.contrib import admin
        from django.urls import path
        from django.conf.urls import url
        from ajax import views

        urlpatterns = [
            path(‘admin/‘, admin.site.urls),
            url(r‘^index‘,views.index),
            url(r‘ajax_receive‘,views.ajax_receive),
        ]

2.2 django的views.py

        from django.shortcuts import render,HttpResponse

        # Create your views here.

        def index(req):
            return  render(req,"index.html")

        def ajax_receive(req):
            return  HttpResponse("hello")

2.3 模板文件 index.html

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

        <script>
            // 生成一個xml對象
            function createXMLHttpRequest() {
                var xmlHttp;
                // 適用於大多數瀏覽器,以及IE7和IE更高版本
                try {
                    xmlHttp = new XMLHttpRequest();
                } catch (e) {
                    //適用於IE6
                    try {
                        xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (e) {
                        //適用於IE5.5,以及IE更早版本
                        try {
                            xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                        } catch (e) {}
                    }
                }
                return xmlHttp;
            }

            // 實例化對象,打開連接,發送數據,返回數據
            function func1 () {
                //step1
                var xmlhttp = createXMLHttpRequest()        // 實例對象

                //step2
                xmlhttp.open("GET","/ajax_receive",true)    // 參數1:請求方式;參數二:請求接口;參數三:采用異步

                //step3
                xmlhttp.send(null);     // 發送數據

                //step4
                xmlhttp.onreadystatechange=function () {
                    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        // alert(xmlhttp.status)     //返回HTTP碼狀態
                        // alert(xmlhttp.readyState) //返服務器響應狀態,4位響應結束

                        var data = xmlhttp.responseText
                        alert(data)
                    }
                }
            }

        </script>
        </body>
        </html>

三. ajax第二樣例,發送post請求

3.1 django的urls.py

        from django.contrib import admin
        from django.urls import path
        from django.conf.urls import url
        from ajax import views

        urlpatterns = [
            path(‘admin/‘, admin.site.urls),
            url(r‘^index‘,views.index),
            url(r‘ajax_receive‘,views.ajax_receive),
        ]

3.2 django的views.py

        from django.shortcuts import render,HttpResponse

        # Create your views here.

        def index(req):
            return  render(req,"index.html")

        def ajax_receive(req):
            if req.method == "POST":
                print("req.POST",req.POST)

            return  HttpResponse("hello2")

3.3 模板文件 index.html

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

        <!-- ajax和form都是和後端進行數據交互的,form的enctype和ajax設置請求頭是一個道理,
        但是form是默認就有這個請求頭的,所以我們在寫form的時候不用特意指定請求頭 -->
        <form action="//" method="post" enctype="application/x-www-form-urlencoded">
            <input type="text">
            <input type="text">
        </form>
        <script>
            // 生成一個xml對象
            function createXMLHttpRequest() {
                var xmlHttp;
                // 適用於大多數瀏覽器,以及IE7和IE更高版本
                try {
                    xmlHttp = new XMLHttpRequest();
                } catch (e) {
                    //適用於IE6
                    try {
                        xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (e) {
                        //適用於IE5.5,以及IE更早版本
                        try {
                            xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                        } catch (e) {}
                    }
                }
                return xmlHttp;
            }

            // 實例化對象,打開連接,發送數據,返回數據
            function func1 () {
                //step1
                var xmlhttp = createXMLHttpRequest();        // 實例對象

                //step2
                xmlhttp.open("POST","/ajax_receive",true);    // 參數1:請求方式;參數二:請求接口;參數三:采用異步

                // POST方法需要設置一個請求頭,如果不設置請求頭,Web容器會忽略請求體的內容
                // POST方法需要設置請求頭,是因為要提交的數據需要放在請求體裏面
                // GET方法不需要是因為GET提交的主體是空的
                // 必須放在send之前,open之後,固定的POST參數
                xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                //step3
                // xmlhttp.send(null);     // 發送數據
                xmlhttp.send("name=dashan");  //POST向後臺提交數據

                //step4
                xmlhttp.onreadystatechange=function () {
                    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        // alert(xmlhttp.status)     //返回HTTP碼狀態
                        // alert(xmlhttp.readyState) //返服務器響應狀態,4位響應結束

                        var data = xmlhttp.responseText;
                        alert(data)
                    }
                }
            }

        </script>
        </body>
        </html>

3.4 GET與POST的不同

        3.4.1 open方法改為了POST
        3.4.2 需要提交的數據寫到send裏面
        3.4.3 因為POST的Request體是有數據的,所以必須設置請求頭

四. AJAX第三例(實現用戶名是否已註冊)

4.1 功能介紹

        在註冊表單中,當用戶填寫了用戶名後,把光標移開,會自動向服務器發送異步請求,服務器返回TRUE或False,
        返回true表示這個用戶已經被註冊過,返回false表示沒有註冊過

        客戶端得到服務器返回的結果後,確定是否在用戶名文本框後顯示"用戶名已被註冊"的錯誤信息!

4.2 案例分析

        - 頁面中給出註冊表單
        - 在username表單字段中添加onblur事件,調用send()方法
        - send()方法獲取username表單字段的內容,向服務器發送異步請求,參數為username
        - django的視圖函數:獲取username參數,判斷是否為"yuan",如果是響應true,否則響應false

4.3 代碼
4.3.1 django的urls.py

            from django.contrib import admin
            from django.urls import path
            from django.conf.urls import url
            from ajax import views

            urlpatterns = [
                path(‘admin/‘, admin.site.urls),
                url(r‘ajax_register‘,views.ajax_register),
            ]

4.3.2 django的views.py

            from django.shortcuts import render,HttpResponse

            # Create your views here.

            def ajax_register(req):

                if req.method == "POST":
                    username = req.POST.get("username")

                    if username == "dashan":
                        return HttpResponse("true")

                    return HttpResponse("false")

                return render(req,"register.html")

4.3.3 模板文件 register.html

            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Title</title>
            </head>
            <body>
            <form>
                <p>用戶名:<input type="text" name="username" onblur="func1(this);"></p>
                <span id="error"></span>
                <p>密碼:<input type="password" name="passwd"></p>
                <input type="submit" value="提交">
            </form>

            <script>

                function createXMLHttpRequest() {
                    var xmlHttp;
                    // 適用於大多數瀏覽器,以及IE7和IE更高版本
                    try {
                        xmlHttp = new XMLHttpRequest();
                    } catch (e) {
                        //適用於IE6
                        try {
                            xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
                        } catch (e) {
                            //適用於IE5.5,以及IE更早版本
                            try {
                                xmlHttp = new ActiveXObject(("Microsoft.XMLHTTP"));
                            } catch (e) {}
                        }
                    }
                    return xmlHttp;
                }

                function func1(self) {
                    var username = self.value;

                    var xmlhttp = createXMLHttpRequest();
                    xmlhttp.open("POST","/ajax_register",true);
                    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                    xmlhttp.send("username="+username);  // 如果是變量的話,必須這樣寫,等於號在雙引號裏面

                    xmlhttp.onreadystatechange=function(){
                        if(xmlhttp.readyState==4 && xmlhttp.status==200){

                            var s = xmlhttp.responseText
                            if (s == "true"){
                                document.getElementById("error").innerHTML="用戶名已存在"
                            }
                        }

                    }
                }
            </script>
            </body>
            </html>

AJAX入門學習-2:基於JS的AJAX實現(以Django為例)