AJAX異步的 JavaScript

什麼是AJAX:php

AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。html

AJAX 不是新的編程語言,而是一種使用現有標準的新方法。node

AJAX 是與服務器交換數據並更新部分網頁的藝術,在不從新加載整個頁面的狀況下。web

AJAX 是一種在無需從新加載整個網頁的狀況下,可以更新部分網頁的技術。ajax

AJAX 是一種用於建立快速動態網頁的技術。數據庫

經過在後臺與服務器進行少許數據交換,AJAX 可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。編程

傳統的網頁(不使用 AJAX)若是須要更新內容,必需重載整個網頁面。數組

有不少使用 AJAX 的應用程序案例:新浪微博、Google 地圖、開心網等等。瀏覽器

Google Suggest

在 2005 年,Google 經過其 Google Suggest 使 AJAX 變得流行起來。緩存

Google Suggest 使用 AJAX 創造出動態性極強的 web 界面:當您在谷歌的搜索框輸入關鍵字時,JavaScript 會把這些字符發送到服務器,而後服務器會返回一個搜索建議的列表。

 

建立 XMLHttpRequest 對象

全部現代瀏覽器(IE7+、Firefox、Chrome、Safari 以及 Opera)均內建 XMLHttpRequest 對象。

建立 XMLHttpRequest 對象的語法:

variable=new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對象:

variable=new ActiveXObject("Microsoft.XMLHTTP");

爲了應對全部的現代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。若是支持,則建立 XMLHttpRequest 對象。若是不支持,則建立 ActiveXObject :

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

AJAX - 向服務器發送請求

XMLHttpRequest 對象用於和服務器交換數據。

向服務器發送請求

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

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
方法 描述
open(method,url,async)

規定請求的類型、URL 以及是否異步處理請求。

  • method:請求的類型;GET 或 POST
  • url:文件在服務器上的位置
  • async:true(異步)或 false(同步)
send(string)

將請求發送到服務器。

  • string:僅用於 POST 請求

GET 仍是 POST?

與 POST 相比,GET 更簡單也更快,而且在大部分狀況下都能用。

然而,在如下狀況中,請使用 POST 請求:

  • 沒法使用緩存文件(更新服務器上的文件或數據庫)
  • 向服務器發送大量數據(POST 沒有數據量限制)
  • 發送包含未知字符的用戶輸入時,POST 比 GET 更穩定也更可靠

GET 請求

一個簡單的 GET 請求:

爲了不這種狀況,請向 URL 添加一個惟一的 ID:

xmlhttp.open("GET","demo_get.asp?t=" + ,true);
xmlhttp.send();Math.random()

若是您但願經過 GET 方法發送信息,請向 URL 添加信息:

xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",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");
xmlhttp.send("fname=Bill&lname=Gates");
 
 
方法 描述
setRequestHeader(header,value)

向請求添加 HTTP 頭。

  • header: 規定頭的名稱
  • value: 規定頭的值

異步 - True 或 False?

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

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

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

對於 web 開發人員來講,發送異步請求是一個巨大的進步。不少在服務器執行的任務都至關費時。AJAX 出現以前,這可能會引發應用程序掛起或中止。

經過 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();

服務器響應

如需得到來自服務器的響應,請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。

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

responseText 屬性

若是來自服務器的響應並不是 XML,請使用 responseText 屬性。

responseText 屬性返回字符串形式的響應,所以您能夠這樣使用:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

responseXML 屬性

若是來自服務器的響應是 XML,並且須要做爲 XML 對象進行解析,請使用 responseXML 屬性:

請求 books.xml 文件,並解析響應:

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;
 
 

AJAX - onreadystatechange 事件

onreadystatechange 事件

當請求被髮送到服務器時,咱們須要執行一些基於響應的任務。

每當 readyState 改變時,就會觸發 onreadystatechange 事件。

readyState 屬性存有 XMLHttpRequest 的狀態信息。

下面是 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;
    }
  });
}

AJAX ASP/PHP 實例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function showHint(str)
{
  var xmlhttp;
  if (str.length==0)
  { 
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest)
  {
    // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    // IE6, IE5 瀏覽器執行代碼
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","/try/ajax/gethint.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<h3>在輸入框中嘗試輸入字母 a:</h3>
<form action=""> 
輸入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>提示信息: <span id="txtHint"></span></p> 

</body>
</html>

在輸入框中嘗試輸入字母 a:

輸入姓名:

提示信息:

 

AJAX 服務器頁面 - ASP 和 PHP

由上面的 JavaScript 調用的服務器頁面是 ASP 文件,名爲 "gethint.asp"。

下面,咱們建立了兩個版本的服務器文件,一個用 ASP 編寫,另外一個用 PHP 編寫。

ASP 文件

"gethint.asp" 中的源代碼會檢查一個名字數組,而後向瀏覽器返回相應的名字:

<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"

'get the q parameter from URL
q=ucase(request.querystring("q"))

'lookup all hints from array if length of q>0
if len(q)>0 then
  hint=""
  for i=1 to 30
    if q=ucase(mid(a(i),1,len(q))) then
      if hint="" then
        hint=a(i)
      else
        hint=hint & " , " & a(i)
      end if
    end if
  next
end if

'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
  response.write("no suggestion")
else
  response.write(hint)
end if
%>

 

 
 

PHP 文件

下面的代碼用 PHP 編寫,與上面的 ASP 代碼做用是同樣的。

<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
  $hint="";
  for($i=0; $i<count($a); $i++)
  {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
      if ($hint=="")
      {
        $hint=$a[$i];
      }
      else
      {
        $hint=$hint." , ".$a[$i];
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
  $response="no suggestion";
}
else
{
  $response=$hint;
}

//output the response
echo $response;
?>
相關文章
相關標籤/搜索