經過一個例子瞭解Ajax

 

Ajax指的Asyncronous JavaScript and XMLjavascript

 

Ajax並非什麼新的編程語言, 它是現有一些東西的應用.從它的名稱中就能夠看出來html

 

假如咱們設想, 瀏覽器展現了一個頁面,但須要更新其中小部分信息,這些信息依賴用戶輸入,又須要和服務器交互, 由於要和服務器交互, 可是其實仍是在這個頁面(url), 因此再從新加載整個HTML其實很浪費, 因此出現了Ajax java

 Ajax就是在JavaScript中, 後臺作Http請求, 能夠是異步的也能夠是同步的, 而後動態更新顯示頁面. 固然這個過程咱們感受不太到,由於地址欄並不會有任何變化.jquery

 

Ajax涉及的東西:ajax

  • JavaScript
  • HTTP

 

其實就只有這兩個編程

 

再具體一點:json

  • XMLHttpRequest (是JavaScript Object), 後臺發送HTTP請求
  • JavaScript DOM , 修改HTML來展現信息
  • HTTP請求和服務器交互

 

一個例子 api

 

好比一個經常使用的Ajax用途是在註冊的時候校驗郵箱是否被註冊,或用戶名是否已存在,用戶不用等到整個form都填寫完提交才知道是不是已被註冊.瀏覽器

 

<form action=" " method="post">
<input type="text"  id="email_register"  name="email"  onblur="check_email(this.value)" />
</form>

 

好比這樣一個頁面, 有一個<form>, 咱們再輸入郵箱後, 它就會去校驗這個郵箱是否被註冊了服務器

給<input>綁定一個blur事件, 失去焦點的時候觸發

 

check_email函數:

function check_email(email){
    ajax_request = new XMLHttpRequest();
    ajax_request.onreadystatechange=function(){
         if (ajax_request.readyState==4 && ajax_request.status==200){
              var result = eval(ajax_request.responseText);
                  if (result.status == 'False'){
                        alert("email registered");
                  }
         }
      }
 
    ajax_request.open("GET", '192.168.12.192:8088/accounts/apiValidRegAddress?type=email&address=' + email, true);
    ajax_request.send();
}

 

 

能夠看到用javascript作一個Ajax請求的接口,流程

  • 初始化一個XMLHttpRequest對象 ajax_request.
  • 給ajax_request寫一個readystatechange函數,  每次其readyState改變的時候會被調用
  • open()
  • send() 

 

GET請求的send()不帶參數, 對於POST請求,要發送的數據放在send()的參數中, 若是上面使用POST

ajax_request.send(type="email",  address=email);

 

 

注意到咱們這行語句:

if (ajax_request.readyState==4 && ajax_request.status==200)

 

 

XMLHttpRequest的readyState能夠取值0~4, 記錄當前請求所處的階段

  • 0: request not initialized 
  • 1: server connection established
  • 2: request received 
  • 3: processing request 
  • 4: request finished and response is ready

當readyState爲4, 也就是收到服務器迴應時, 服務器固然是作了一個HTTP應答, status記錄服務器HTTP應答狀態碼, 好比

  • 200  OK
  • 404  頁面缺失

 

 

[學習] : XMLHttpRequest是JavaScript的一個類,它也是一個標準, 更多的學習, 參考XMLHttpRequest的API

 

 

上面例子頁面的完整代碼

<html>
<head>
<script>
        function checkEmail(email){
                var mailPattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                if (!mailPattern.test(email)){
                        alert("invaid email : " + email);
                } else {
                        ajax_request = new XMLHttpRequest();
                        ajax_request.onreadystatechange=function(){
                                        if (ajax_request.readyState==4 && ajax_request.status==200){
                                                var result = eval("("+ajax_request.responseText+")");
                                                if (result.status == false){
                                                        alert("email registered");
                                      }
                                        }
                                }
                        ajax_request.open("GET", '/accounts/apiValidRegAddress?type=email&address=' + email, true);
                        ajax_request.send();

                }
        }
</script>
</head>

<input type="text" onblur="checkEmail(this.value)"/>
</html>

 

在checkEmail()中作了一個郵箱地址是否合法的正則檢查

 

我在本身的Django項目中,加入了這個頁面這個頁面來測試, 上面那個Ajax接口是咱們已經實現了的,檢查用戶輸入的手機或郵箱是否被註冊了.

 

頁面截圖:

 

 

 

JQuery的Ajax

jquery有一系列和Ajax相關的函數,其中最主要的是  jquery.ajax()

語法

  • jquery.ajax([setting])

setting就是一系列的參數,好比

  • type    'GET' or 'POST'
  • url       請求的url
  • data    傳遞到服務器的數據, key/value的形式
  • sucess  請請求成功的回調函數, 參數是整個ajax調用返回的數據, 而且已經根據 dataType轉成了相應的類型
  • dataType    預計的調用返回數據的類型, 如 'json'

好比上面的例子,用ajax來寫就是

1 jquery.ajax(type='GET', 
2             url = '/accounts/apiValidRegAddress', 
3             data={'type':'email', 'address': email},
4             dataType='json',
5             sucess = function(result){
6             if (result.status == false){
7                   alert('email registered');
8             }
9 })

 

 

 

--------------------------

參考:

w3cshools的教程

http://www.w3schools.com/ajax/

mozilla development network

http://mdn.beonex.com/en/AJAX.html

相關文章
相關標籤/搜索