使用php和ajax实时获取数据
问题描述:
我想从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>
答
像这样的东西(-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
大声笑,所以我们应该写整个代码为您服务。如果你有一个特定的事情你坚持不懈,这是超越懒惰 – Akintunde007
,我会更愿意帮助。但是,这个问题很广泛。 – ArtisticPhoenix
欢迎使用堆栈溢出。请阅读[我如何问一个好问题?](https://*.com/help/how-to-ask)。向我们展示你迄今为止的努力。 – pirho