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 表格返回结果: