Ajax的使用四大詳細步驟

才智咖 人氣:5.17K

什麼是ajax?

Ajax的使用四大詳細步驟

ajax(非同步javascript xml) 能夠重新整理區域性網頁資料而不是重新載入整個網頁。

如何使用ajax?

第一步,建立xmlhttprequest物件,var xmlhttp =new XMLHttpRequest();XMLHttpRequest物件用來和服務器交換資料。

var xhttp;if (ttpRequest) {//現代主流瀏覽器xhttp = new XMLHttpRequest();} else {// 針對瀏覽器,比如IE5或IE6xhttp = new ActiveXObject("TTP");}

第二步,使用xmlhttprequest物件的open()和send()方法傳送資源請求給伺服器。

(method,url,async) method包括get 和post,url主要是檔案或資源的路徑,async引數為true(代表非同步)或者false(代表同步)

();使用get方法傳送請求到伺服器。

(string);使用post方法傳送請求到伺服器。

post 傳送請求什麼時候能夠使用呢?

(1)更新一個檔案或者資料庫的時候。

(2)傳送大量資料到伺服器,因為post請求沒有字元限制。

(3)傳送使用者輸入的加密資料。

get例子:

("GET", "ajax_", true);("GET", "", true);("GET", "demo_" + om(), true);();

post例子

("POST", "demo_", true);();

post表單資料需要使用xmlhttprequest物件的setRequestHeader方法增加一個HTTP頭。

post表單例子

("POST", "ajax_", true);equestHeader("Content-type", "application/x-www-form-urlencoded");("fname=Henry&lname=Ford");

async=true 當伺服器準備響應時將執行onreadystatechange函式。

adystatechange = function() {if (yState == 4 && us == 200) {lementById("demo")rHTML = onseText;}};("GET", "", true);();

asyn=false 則將不需要寫onreadystatechange函式,直接在send後面寫上執行程式碼

("GET", "", false);();lementById("demo")rHTML = onseText;

第三步,使用xmlhttprequest物件的onseText或responseXML屬性獲得伺服器的響應。

使用responseText屬性得到伺服器響應的字串資料,使用responseXML屬性得到伺服器響應的XML資料。

例子如下:

lementById("demo")rHTML = onseText;

伺服器響應的XML資料需要使用XML物件進行轉換。

例子:

xmlDoc = onseXML;txt = "";x = lementsByTagName("ARTIST");for (i = 0; i < th; i++) {txt += x[i]dNodes[0]Value + "

";}lementById("demo")rHTML = txt;

第四步,onreadystatechange函式,當傳送請求到伺服器,我們想要伺服器響應執行一些功能就需要使用onreadystatechange函式,每次xmlhttprequest物件的readyState發生改變都會觸發onreadystatechange函式。

onreadystatechange屬性儲存一個當readyState發生改變時自動被呼叫的函式。

readyState屬性,XMLHttpRequest物件的狀態,改變從0到4,0代表請求未被初始化,1代表伺服器連線成功,2請求被伺服器接收,3處理請求,4請求完成並且響應準備。

status屬性,200表示成功響應,404表示頁面不存在。

在onreadystatechange事件中,伺服器響應準備的時候發生,當readyState==4和status==200的時候伺服器響應準備。

例子:

function loadDoc() {var xhttp = new XMLHttpRequest();adystatechange = function() {if (yState == 4 && us == 200) {lementById("demo")rHTML = onseText;}};("GET", "ajax_", true);();} //函式作為引數呼叫

Let AJAX change this text.

Change Content

function loadDoc(url, cfunc) {var xhttp;xhttp=new XMLHttpRequest();adystatechange = function() {if (yState == 4 && us == 200) {cfunc(xhttp);}};("GET", url, true);();}function myFunction(xhttp) {lementById("demo")rHTML = onseText;}

TAGS:Ajax 四大