1. 程式人生 > >Day67:JS實現的ajax

Day67:JS實現的ajax

tex let 參數 rom exe 自動 否則 sync 註冊表

JS實現的ajax

AJAX核心(XMLHttpRequest)

其實AJAX就是在Javascript中多添加了一個對象:XMLHttpRequest對象。所有的異步交互都是使用XMLHttpServlet對象完成的。也就是說,我們只需要學習一個Javascript的新對象即可。

?
1 var xmlHttp = new XMLHttpRequest();(大多數瀏覽器都支持DOM2規範)

註意,各個瀏覽器對XMLHttpRequest的支持也是不同的!為了處理瀏覽器兼容問題,給出下面方法來創建XMLHttpRequest對象:

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

使用流程

步驟1: 打開與服務器的連接(open方法)

當得到XMLHttpRequest對象後,就可以調用該對象的open()方法打開與服務器的連接了。open()方法的參數如下:

open(method, url, async)

  • method:請求方式,通常為GETPOST
  • url:請求的服務器地址,例如:/ajaxdemo1/AServlet,若為GET請求,還可以在URL後追加參數;
  • async:這個參數可以不給,默認值為true,表示異步請求;
?
1 2 var xmlHttp = createXMLHttpRequest(); xmlHttp.open("GET", "/ajax_get/", true); 

步驟2: 發送請求

當使用open打開連接後,就可以調用XMLHttpRequest對象的send()方法發送請求了。send()方法的參數為POST請求參數,即對應HTTP協議的請求體內容,若是GET請求,需要在URL後連接參數。

註意:若沒有參數,需要給出null為參數!若不給出null為參數,可能會導致FireFox瀏覽器不能正常發送請求!

?
1 xmlHttp.send(null);

步驟3: 接收服務器響應

當請求發送出去後,服務器端就開始執行了,但服務器端的響應還沒有接收到。接下來我們來接收服務器的響應。

XMLHttpRequest對象有一個onreadystatechange事件,它會在XMLHttpRequest對象的狀態發生變化時被調用。下面介紹一下XMLHttpRequest對象的5種狀態:

  • 0:初始化未完成狀態,只是創建了XMLHttpRequest對象,還未調用open()方法;
  • 1:請求已開始,open()方法已調用,但還沒調用send()方法;
  • 2:請求發送完成狀態,send()方法已調用;
  • 3:開始讀取服務器響應;
  • 4:讀取服務器響應結束。

onreadystatechange事件會在狀態為1234時引發。

  下面代碼會被執行四次!對應XMLHttpRequest的四種狀態!

xmlHttp.onreadystatechange = function() {
            alert(‘hello‘);
        };

但通常我們只關心最後一種狀態,即讀取服務器響應結束時,客戶端才會做出改變。我們可以通過XMLHttpRequest對象的readyState屬性來得到XMLHttpRequest對象的狀態。

xmlHttp.onreadystatechange = function() {
            if(xmlHttp.readyState == 4) {
                alert(‘hello‘);    
            }
        };

其實我們還要關心服務器響應的狀態碼是否為200,其服務器響應為404,或500,那麽就表示請求失敗了。我們可以通過XMLHttpRequest對象的status屬性得到服務器的狀態碼。

最後,我們還需要獲取到服務器響應的內容,可以通過XMLHttpRequest對象的responseText得到服務器響應內容。

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

if 發送POST請求

<1>需要設置請求頭:xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)註意 :form表單會默認這個鍵值對不設定,Web服務器會忽略請求體的內容。

<2>在發送時可以指定請求體了:xmlHttp.send(“username=yuan&password=123”)

JS實現ajax小結

技術分享
/*
    創建XMLHttpRequest對象;
    調用open()方法打開與服務器的連接;
    調用send()方法發送請求;
    為XMLHttpRequest對象指定onreadystatechange事件函數,這個函數會在

    XMLHttpRequest的1、2、3、4,四種狀態時被調用;

    XMLHttpRequest對象的5種狀態,通常我們只關心4狀態。

    XMLHttpRequest對象的status屬性表示服務器狀態碼,它只有在readyState為4時才能獲取到。

    XMLHttpRequest對象的responseText屬性表示服務器響應內容,它只有在
    readyState為4時才能獲取到!


*/
技術分享

測試代碼:

技術分享 技術分享
<h1>AJAX</h1>
<button onclick="send()">測試</button>
<div id="div1"></div>


<script>
       function createXMLHttpRequest() {
            try {
                return new XMLHttpRequest();//大多數瀏覽器
            } catch (e) {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        }

        function send() {
            var xmlHttp = createXMLHttpRequest();
            xmlHttp.onreadystatechange = function() {
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    var div = document.getElementById("div1");
                    div.innerText = xmlHttp.responseText;
                    div.textContent = xmlHttp.responseText;
                }
            };

            xmlHttp.open("POST", "/ajax_post/", true);
            //post: xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttp.send(null);  //post: xmlHttp.send("b=B");
        }


</script>
       
#--------------------------------views.py 
from django.views.decorators.csrf import csrf_exempt

def login(request):
    print(‘hello ajax‘)
    return render(request,‘index.html‘)

@csrf_exempt   #csrf防禦
def ajax_post(request):
    print(‘ok‘)
    return HttpResponse(‘helloyuanhao‘) 
技術分享

實例(用戶名是否已被註冊)

7.1 功能介紹

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

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

7.2 案例分析

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

參考代碼:

技術分享
<script type="text/javascript">
        function createXMLHttpRequest() {
            try {
                return new XMLHttpRequest();
            } catch (e) {
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
        }

        function send() {
            var xmlHttp = createXMLHttpRequest();
            xmlHttp.onreadystatechange = function() {
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    if(xmlHttp.responseText == "true") {
                        document.getElementById("error").innerText = "用戶名已被註冊!";
                        document.getElementById("error").textContent = "用戶名已被註冊!";
                    } else {
                        document.getElementById("error").innerText = "";
                        document.getElementById("error").textContent = "";
                    }
                }
            };
            xmlHttp.open("POST", "/ajax_check/", true, "json");
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var username = document.getElementById("username").value;
            xmlHttp.send("username=" + username);
        }
</script>

//--------------------------------------------------index.html

<h1>註冊</h1>
<form action="" method="post">
用戶名:<input id="username" type="text" name="username" onblur="send()"/><span id="error"></span><br/>
密 碼:<input type="text" name="password"/><br/>
<input type="submit" value="註冊"/>
</form>


//--------------------------------------------------views.py
from django.views.decorators.csrf import csrf_exempt

def login(request):
    print(‘hello ajax‘)
    return render(request,‘index.html‘)
    # return HttpResponse(‘helloyuanhao‘)

@csrf_exempt
def ajax_check(request):
    print(‘ok‘)

    username=request.POST.get(‘username‘,None)
    if username==‘yuan‘:
        return HttpResponse(‘true‘)
    return HttpResponse(‘false‘)
View Code

Day67:JS實現的ajax