2017-10-29 62 views
-3

我想從mysql中的頁面中獲取所有用戶的名稱,並且一旦點擊了名稱,他們的電子郵件ID應該實時顯示。使用php和ajax實時獲取數據

的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> 
+3

大聲笑,所以我們應該寫整個代碼爲您服務。如果你有一個特定的事情你堅持不懈,這是超越懶惰 – Akintunde007

+1

,我會更願意幫助。但是,這個問題很廣泛。 – ArtisticPhoenix

+0

歡迎使用堆棧溢出。請閱讀[我如何問一個好問題?](https://stackoverflow.com/help/how-to-ask)。向我們展示你迄今爲止的努力。 – pirho

回答

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

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