ajax簡單使用_1

瞭解流程:

1.創建 xmlHttpRequest對象

現代所有瀏覽器都支持xmlHttpRequest對象  IE5  IE6 的卻只能是ActiveXObject
XMLHttpRequest用於在後臺與服務器交換數據 以爲可以不在加載整個頁面情況下 更新部分內容

創建語法對象 

varriable = new XmlHttpRequest();

#關於<script>標籤 目前html5 默認腳本語言 不用再去 填寫 type

<script type="javascript">

    var myAjax ;

    if (window.XMLHttpRequest){
        /*code for IE7+ FireFox chrome ......*/
        myAjax = new XMLHttpRequest();
    }else{
        /*code for ie5 ie 6*/
        myAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
</script>


2.XMLHttpRequest (XHR) 對象用於服務器交換數據

向服務器發送請求
如需將請求發送到服務器  我們使用XMLHttpRequest對象的open() 和 send()方法

xmlhttp.open("GET","test11.txt",true);
xmlhttp.send(string);

方法                                       描述
open(method,url,async)        規定請求的類型、URL 以及是否異步處理請求。

method:                              請求的類型; GET 或 POST    

 url:                                     文件在服務器上的位置
 async:                                true(異步)或 false(同步)

send(string)                           將請求發送到服務器。

string:                                  僅用於 POST 請求
GET方法簡單也更快 並且大部分時間都是使用

如下情況使用POST
無法使用緩存文件(更新服務器上的文件或者數據庫)
向服務器發送大量數據(POST沒有數據量限制)
發送包含位置字符的用戶輸入是,POST比GET更穩定、更可靠


GET請求

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();

可以添加信息
xmlhttp.open("GET","demo_get.asp?fname=Bill?lname=Gate",true);
xmlhttp.send();


POST請求


一個簡單的POST請求:

xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();


如果需要像 HTML 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 HTTP 頭。然後在 send() 方法中規定您希望發送的數據:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); http頭信息
xmlhttp.send("fname=Bill&lname=Gates");

方法
setRequestHeader(header,value)
向請求添加http頭
header 規定頭名稱
value  規定頭的值

url - 服務器上的文件
open() 方法的 url 參數是服務器上文件的地址:

xmlhttp.open("GET","ajax_test.asp",true);
該文件可以是任何類型的文件,比如 .txt 和 .xml,或者服務器腳本文件,比如 .asp 和 .php (在傳回響應之前,能夠在服務器上執行任務)。

異步 - True 或 False?


AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 對象如果要用於 AJAX 的話,其 open() 方法的 async 參數必須設置爲 true:

xmlhttp.open("GET","ajax_test.asp",true);

通過 AJAX,JavaScript 無需等待服務器的響應,而是:

在等待服務器響應時執行其他腳本
當響應就緒後對響應進行處理

Async = true
當使用 async=true 時,請規定在響應處於 onreadystatechange 事件中的就緒狀態時執行的函數:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

 

Async = false
如需使用 async=false,請將 open() 方法中的第三個參數改爲 false:

xmlhttp.open("GET","test1.txt",false);
我們不推薦使用 async=false,但是對於一些小型的請求,也是可以的。

請記住,JavaScript 會等到服務器響應就緒才繼續執行。如果服務器繁忙或緩慢,應用程序會掛起或停止。

註釋:當您使用 async=false 時,請不要編寫 onreadystatechange 函數 - 把代碼放到 send() 語句後面即可:

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


3.服務器響應
使用 XMLHttpRequest 對象的 responseText 或者 reponseXML屬性


屬性                  描述
responseText    獲得字符串形式的響應數據。
responseXML   獲得 XML 形式的響應數據。

reponseText屬性

如果來自服務器的響應並非 XML,請使用 responseText 屬性。

responseText 屬性返回字符串形式的響應,因此可以使用:
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;


reponseXML屬性
如果服務器的響應是xml  且需要XML對象進行解析,請使用reponseXML屬性

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

xml文檔:

<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>

4.XHR readyState
onreadystatechange
每當readyState改變 就會觸發onreadyStateChange事件

readyState 屬性存有XMLHttpRequest的狀態信息

三個重要熟悉:
屬性               描述
onreadystatechange 存儲函數 或者函數名 每當readyState屬性改變時,就會調用該函數

readyState          存有XMLHttpRequest的狀態,從0到4發生變化
                            0: 請求未初始化
                            1: 服務器連接已建立
                            2: 請求已接收
                            3: 請求處理中
                            4: 請求已完成,且響應已就緒

status                  200:“OK”
                            404 :未找到頁面
                    
在 onreadystatechange事件中 規定服務器響應已做好被處理的準備時做執行的任務
當readyState等於4 且狀態爲200時,表示響應已就緒

xmlhttp.onreadystatechange=function(){

    if(xmlhttp.readyState == 4 && xmlhttp.status==200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }

}

註釋:onreadystatechange 事件被觸發 5 次(0 - 4),對應着 readyState 的每個變化。

使用callback函數

callback函數是一種以參數形式傳遞給另一個函數的函數
如果網站存在多個AJAX任務,那麼應該創建XMLHttpRequest對象編寫一個標準的函數併爲每個AJAX任務調用該函數
該函數調用應該包含 URL 以及發生 onreadystatechange 事件時執行的任務(每次調用可能不盡相同):

function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章