使用等待/异步函数获取显示数据

rgh9267

我正在为(我猜)一个简单的问题寻求帮助。我一直在寻找这个答案,但我没有找到这个问题的任何答案。我很难找到一种方法来选择我的数组的 2 个电子邮件地址和 2 条消息并将它们显示在 div 中

这个想法是有这个演示:

电子邮件 1 消息 1

电子邮件 2 消息 2

这是我的 php :

<?php 
session_start();

try{
  $bdd = new PDO('mysql:host=localhost;dbname=XXX;charset=UTF8;', 'root', '');

  }

catch(Exception $e){
  die('Erreur : '.$e->getMessage());
}


$message = $bdd->prepare("SELECT emailaddress, message FROM messages");

$message->execute();

$results = $message->fetchAll(PDO::FETCH_ASSOC);

$json = json_encode($results);


header("content-type:application/json");
echo $json;
exit();

 ?>


这是我的 JSON:


    async function updateDisplay() {
        const reponse = await fetch (url);
        const data = await reponse.text();
        const dataObject = JSON.parse(data);

      console.log(dataObject);
}
updateDisplay()

结果在我的控制台中:


0: "[email protected]"
1: "test message" 
email: "[email protected]"
message: "[email protected] test message"

<prototype>: Object { … }

1: {…}

0: "[email protected]"
1: "message 2"
email: "[email protected]"
message: "message test 2"

<prototype>: Object { … }

非常感谢你的帮助

rgh9267

这是我的问题的解决方案:

    async function updateDisplay() {
        const response = await fetch ('http://localhost/xxxxx/fetch.php');
        const data = await response.text();
        const dataObject = JSON.parse(data);

        console.log(dataObject);

      let li = `<tr><th></th> <td> </td> <th></th></tr>`; 
        

        dataObject.forEach(user => { 
            li += `<tr> 
                <td>${user.email} </td> 
                <td>${user.message}</td>          
            </tr>`; 
        }); 
   

    document.getElementById("chat").innerHTML = li; 
 }
   
setInterval(updateDisplay, 1000);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章