Ajax入门例子

来源:互联网 发布:网络技术服务合同范本 编辑:程序博客网 时间:2024/04/20 19:09
          在customer.php的文件中,代码如下:


<html>
<head>


<script type="text/javascript">
function showCustomer(str)
{
 var xmlhttp;  


if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
else
  {// code for 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","/test/getcustomer.php?q="+str,true);//这里的url是指你的文件路径,例如,我的customer.php和getcustomer.php都在www下的test文件                                                                                                          目录下,所以就写成了此种形式
   xmlhttp.send();
}
</script>


</head>
<body>
<form action="" style="margin-top:15px;"> 
<label>请选择一位客户:
<select name="customers" onchange="showCustomer(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
<option value="APPLE">Apple Computer, Inc.</option>
<option value="BAIDU ">BAIDU, Inc</option>
<option value="Canon">Canon USA, Inc.</option>
<option value="Google">Google, Inc.</option>
<option value="Nokia">Nokia Corporation</option>
<option value="SONY">Sony Corporation of America</option>
</select>
</label>
</form>
<br />
<div>客户信息将在此处列出 ...</div>
<div id="txtHint"></div>


</body>
</html>




  在getcustomer.php的文件中,代码如下:


<?php
$q=$_GET["q"];


$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }


mysql_select_db("test", $con);


$sql="SELECT * FROM user1 WHERE  firstname= '".$q."'";
//var_dump($sql);
$result = mysql_query($sql);


echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
 echo "<tr>";
 echo "<td>" . $row['firstname'] . "</td>";
 echo "<td>" . $row['lastname'] . "</td>";
 echo "<td>" . $row['age'] . "</td>";
 echo "<td>" . $row['hometown'] . "</td>";
 echo "<td>" . $row['Job'] . "</td>";
 echo "</tr>";
}
echo "</table>";


mysql_close($con);
?>
//数据库是test, 表是user1,一共有五个字段,分别是firstname,lastname,age,hometown和Job


最后能实现页面无刷新字段的变化的效果!刚学Ajax,感觉很不错!
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 科目二考试第一次不合格怎么办 科目二不想考了怎么办 科二有事考不了怎么办 科四有事去不了怎么办 社保卡发了密码怎么办 不知道社保卡号怎么办 科目三未到30天怎么办 户口地址变了驾照怎么办 拿了驾照没开车怎么办 免检的车在外地怎么办 2018年b2证扣3分怎么办 科一考试没去怎么办 上海房子卖了户口怎么办 贷款买房买房人不是贷款人怎么办 行驶证驾驶证都遗失了怎么办 c1增驾b2没考过怎么办 没驾照买车怎么办行驶证 广州车辆年审加装踏板怎么办 租车感觉违章了 怎么办 武汉驾照扣12分怎么办 驾驶证照片泡水不清楚怎么办 驾驶证过了180天怎么办 天津有公司执照怎么办落户 温州车在上海年审手续怎么办 广东小高考考了d怎么办 深圳开摩托抓到怎么办 深圳车卖了车牌怎么办 a1驾照时期过了怎么办 b1驾照扣了12分怎么办 北京的驾照换证怎么办 b2汽车驾驶证年审过期几天怎么办 上海驾照到期人在外地怎么办 交警开的罚单交不了怎么办 珠海交警微信交罚单扣分怎么办 驾驶证违法罚款单子没有了怎么办 转账密码输错3次怎么办 汽车违章扣6分怎么办 汽车扣了72分年检怎么办 汽车扣了50分怎么办 汽车扣了15分怎么办 汽车扣了27分怎么办