【问题标题】:display data with await/async function fetch使用等待/异步函数获取显示数据
【发布时间】:2020-10-03 12:14:40
【问题描述】:

我正在为(我猜)一个简单的问题寻求帮助。我一直在寻找这个答案,但我没有找到这个问题的任何答案。 我很难找到一种方法来选择我的数组的 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: "th@hotmail.fr"
1: "test message" 
email: "th@hotmail.fr"
message: "th@hotmail.fr test message"

<prototype>: Object { … }

1: {…}

0: "2@hotmail.fr"
1: "message 2"
email: "2@hotmail.fr"
message: "message test 2"

<prototype>: Object { … }

非常感谢您的帮助

【问题讨论】:

    标签: php arrays json fetch fetch-api


    【解决方案1】:

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

        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);

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 2019-07-29
      • 2021-07-07
      • 2023-03-13
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多