AJAX Database 示例 | Database Cases

Ajax教程


AJAX 可用来与数据库进行动态通信。


AJAX 数据库实例

下面的例子将演示网页如何通过 AJAX 从数据库读取信息: 请在下面的下拉列表中选择一个客户:


客户信息将显示在这…

亲自试试


示例解析 – showCustomer() 函数

当用户在上面的下拉列表中选择某个客户时,会执行名为 “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 (带有输入域中的内容)

AJAX 服务器页面

由上面的 JavaScript 调用的服务器页面是 PHP 文件,名为 “getcustomer.php”。

用 PHP 编写服务器文件也很容易,或者用其他服务器语言。请看用 PHP 编写的相应的例子

“getcustomer.php” 中的源代码负责对数据库进行查询,然后返回结果:

<?php

$q = isset($_GET["q"]) ? $_GET["q"] : '';

if(empty($q)) {
    echo '请选择一个客户';
    exit;
}

$con = mysqli_connect('localhost','test','test');

if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

// 选择数据库
mysqli_select_db($con,"test");

// 设置编码,防止中文乱码
mysqli_set_charset($con, "utf8");

$sql="SELECT * FROM customers WHERE CustomerID = '".$q."'";

$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result))
{
    echo "CustomerID:" . $row['CustomerID'] . "<br>";
    echo "CompanyName:" . $row['CompanyName'] . "<br>";
    echo "ContactName:" . $row['ContactName'] . "<br>";
    echo "Address:" . $row['Address'] . "<br>";
    echo "City:" . $row['City'] . "<br>";
    echo "PostalCode:" . $row['PostalCode'] . "<br>";
    echo "Country:" . $row['Country'] . "<br>";
}

mysqli_close($con);

?>

Ajax教程


相关