【问题标题】:data fetching in real time using php and ajax使用 php 和 ajax 实时获取数据
【发布时间】:2017-10-29 07:54:01
【问题描述】:

我想从 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>

【问题讨论】:

  • 大声笑,所以我们应该为您编写整个代码。这超越了懒惰
  • 如果你有一个特定的事情你被困住了,我会更愿意提供帮助。然而,这个问题的范围很广。
  • 欢迎来到 Stack Overflow。请阅读How do I ask a good question?。向我们展示你迄今为止的努力。
  • @artisticphoenix 我已经获取了所有用户,并且还可以显示特定的电子邮件,但那是在新页面中并且每次刷新时。
  • @sammaity - 我怎么知道,读心术。您需要提供一些代码和一些输入数据,以及一些预期的输出数据。等等

标签: php mysql ajax


【解决方案1】:

类似这样的东西(-注意-我根本没有测试过,但这是基本思想)

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

阿贾克斯 - https://www.w3schools.com/xml/ajax_intro.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2019-01-27
    • 2011-08-26
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多