使用php和ajax实时获取数据

时间:2017-10-29 07:54:02

标签: php mysql ajax

我想从mysql中获取页面中的所有用户名,并且一旦点击了名称,他们的电子邮件ID就会实时显示。

new.php和email.php如下:

<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect('localhost','root','','test');
$sql="select * from users";
$res=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($res)){
?>
<a href="email.php?id=<?php echo $row['id']; ?>"> <?php echo $row['name'] ?>
</a><br />

<?php

}


?>
</body>
</html>



<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect('localhost','root','','test');
$id=$_GET['id'];
$sql="select * from users where id= '$id'";
$res=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($res)){
echo $row['email'];
}


?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这样的东西(-note-我根本没有测试过这个,但这是基本的想法)

page.php文件

<html>
    <head>
        <script type="text/javascript">
               function getLinks(){
                    //use ajax to get the links
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() {
                        if (this.readyState == 4 && this.status == 200) {   
                          document.getElementById("link_wrapper").innerHTML = this.responseText;
                        }
                    };
                    xhttp.open("GET", "get_user_email.php", true);
                    xhttp.send();
                }

                setInterval( function(){
                    //call getLinks every 5000 milliseconds
                    getLinks();
                },5000);

                //call getLinks on page load
                window.onload = getLinks;
        </script>
    </head>
    <body>
        <div id="link_wrapper"></div>
    </body>
</html>

get_user_email.php

<?php
    $con=mysqli_connect('localhost','root','','test');
    $sql="select * from users";
    $res=mysqli_query($con,$sql);
    $html = '';

    while($row=mysqli_fetch_array($res)){
        $html .= '<a href="email.php?id='.$row['id'].'">'.$row['name'].'</a><br />';
    }

    echo $html;

供参考:

setInterval - https://www.w3schools.com/jsref/met_win_setinterval.asp

Ajax - https://www.w3schools.com/xml/ajax_intro.asp