天天看點

AJAX Database 執行個體

AJAX 可用來與資料庫進行動态通信。

下面的例子将示範網頁如何通過 AJAX 從資料庫讀取資訊:

請在下面的下拉清單中選擇一個客戶:

Apple Computer, Inc.

BAIDU, Inc

Canon USA, Inc.

Google, Inc.

Nokia Corporation

Sony Corporation of America

客戶資訊将顯示在這...

當使用者在上面的下拉清單中選擇某個客戶時,會執行名為 "showCustomer()" 的函數。該函數由 "onchange" 事件觸發:

function showCustomer(str)

{

var xmlhttp;

if (str=="")

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/getcustomer.php?q="+str,true);

xmlhttp.send();

showCustomer() 函數執行以下任務:

檢查是否已選擇某個客戶

建立 XMLHttpRequest 對象

當伺服器響應就緒時執行所建立的函數

把請求發送到伺服器上的檔案

請注意我們向 URL 添加了一個參數 q (帶有輸入域中的内容)

由上面的 JavaScript 調用的伺服器頁面是 PHP 檔案,名為 "getcustomer.php"。

用 PHP 編寫伺服器檔案也很容易,或者用其他伺服器語言。請看用 PHP 編寫的相應的例子。

"getcustomer.php" 中的源代碼負責對資料庫進行查詢,然後用 HTML 表格傳回結果: