开发学院

您的位置:首页>教程>正文

教程正文

AJAX 数据库操作

AJAX 数据库操作

为了更好地说明使用Ajax从数据库访问信息是多么容易,我们将构建MySQL查询,并在“ajax.html”上显示结果。但在我们开始之前,我们先做一些基础工作。使用以下命令创建一个表。


注意:我们假设您有足够的特权来执行以下MySQL操作

CREATE TABLE 'ajax_example' (
   'name' varchar(50) NOT NULL,
   'age' int(11) NOT NULL,
   'sex' varchar(1) NOT NULL,
   'wpm' int(11) NOT NULL,
   PRIMARY KEY  ('name')
)

使用以下SQL语句填充数据:

INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);
INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);

客户端html文件

新建一个ajax.html文件,输入下面代码.

<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
   var ajaxRequest;  // The variable that makes Ajax possible!
   try{
   
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
   }catch (e){
      
      // Internet Explorer Browsers
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
         
         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){
         
            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
   }
   
   // Create a function that will receive data
   // sent from the server and will update
   // div section in the same page.
   ajaxRequest.onreadystatechange = function(){
   
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
      }
   }
   
   // Now get the value from user and pass it to
   // server script.
   var age = document.getElementById('age').value;
   var wpm = document.getElementById('wpm').value;
   var sex = document.getElementById('sex').value;
   var queryString = "?age=" + age ;
   
   queryString +=  "&wpm=" + wpm + "&sex=" + sex;
   ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
   ajaxRequest.send(null); 
}
//-->
</script>

<form name='myForm'>

   Max Age: <input type='text' id='age' /> <br />
   Max WPM: <input type='text' id='wpm' /> <br />
   Sex: 
   <select id='sex'>
      <option value="m">m</option>
      <option value="f">f</option>
   </select>
   <input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
   
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

注意:查询中的变量传递方式为Http GET,如下。

URL?variable1=value1;&variable2=value2;

服务器端php文件

  现在,客户端html文件准备好了,我们接着编写服务器端脚本,它将从数据库中获取年龄、名字和性别,并将其发送回客户端。创建ajax-example.php文件并输入如下代码:

<?php
$dbhost = "localhost";//这里写你的数据库ip地址
$dbuser = "dbusername";//这里写你的数据库账号
$dbpass = "dbpassword";//这里写你的数据库密码
$dbname = "dbname";//这里写数据库名称
//连接到mysql
mysql_connect($dbhost, $dbuser, $dbpass);
//选择数据库
mysql_select_db($dbname) or die(mysql_error());
// 从Query String中接受值
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
//转换危险的字符,以防止sql注入攻击
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//构建查询
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
//判断变量类型是否为数字
if(is_numeric($age))
   $query .= " AND age <= $age";

if(is_numeric($wpm))
   $query .= " AND wpm <= $wpm";
//执行查询
$qry_result = mysql_query($query) or die(mysql_error());

//生成结果
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// 循环输出
while($row = mysql_fetch_array($qry_result)){
   $display_string .= "<tr>";
   $display_string .= "<td>$row[name]</td>";
   $display_string .= "<td>$row[age]</td>";
   $display_string .= "<td>$row[sex]</td>";
   $display_string .= "<td>$row[wpm]</td>";
   $display_string .= "</tr>";
}

echo "Query: " . $query . "<br />";
$display_string .= "</table>";
//输出结果
echo $display_string;
?>

如果您代码写的没问题,并且数据库配置没问题,那么您应该可以看到结果已经显示在网页上面了.