使用ajax,php和mysql数据库交互

先建立一个页面ajax.html,包括一个下拉菜单,内容改变时传递给PHP页面查询数据库,反馈结果。
<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript">
            function select(obj)
            {
                if(window.XMLHttpRequest)
                {
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {
                    xmlhttp=new ActiveXObect("Microsoft.XMLHTTP");
                }
                xmlhttp.open("GET","data.php?q="+obj,true);
                xmlhttp.send();
                xmlhttp.onreadystatechange=function()
                {
                    if(xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                    }
                }
            }
        </script>
    </head>
    <body>
        <select οnchange="select(this.value)">
            <option selected="selected">nanchang</option>
            <option>shanghai</option>
            <option>beijing</option>
            <option>shenzhen</option>
        </select>
        <div id="txtHint" align="center">
            
        </div>
    </body>
</html>
 

 

建立一个页面data.php,通过echo 打印输出的结果会显示回ajax.html
<?php
$a=$_GET["q"];
$link = mysql_connect("localhost","root","123456");
  if(!$link)
  {
      die('数据库连接失败:'.mysql_error());
  }
  if(!mysql_select_db("test"))
  {
      die('数据库选择失败:'.mysql_error());
  }
  echo '<table width="100%" border="0">';
  echo '<tr>';
  echo '<th width="10%">ID</th>';
  echo '<th width="10%">Name</th>';
  echo '<th width="10%">Password</th>';
  echo '</tr>';
     
    $sql="select * from user where name='{$a}'";
    $resultest=mysql_query($sql);
    
    if($resultest&&mysql_num_rows($resultest)>0)
    {
        while (list($id,$name,$password)=mysql_fetch_row($resultest))
                {
                    echo "<tr>";
                    echo '<th width="10%">ID</th>';
                    echo '<th width="10%">Name</th>';
                    echo '<th width="10%">Password</th>';
                    echo "</tr>";
                }
    }
  
?>

转载于:https://my.oschina.net/u/3377291/blog/884715

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值