使用 await/async 函数 fetch 显示数据

我正在为(我猜)一个简单的问题寻求帮助。我一直在寻找这个答案,但我没有找到这个问题的任何答案。我很难找到一种方法来选择数组中的 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 { … }

非常感谢你的帮助


千万里不及你
浏览 225回答 1
1回答

MMTTMM

这是我的问题的解决方案:&nbsp; &nbsp; async function updateDisplay() {&nbsp; &nbsp; &nbsp; &nbsp; const response = await fetch ('http://localhost/xxxxx/fetch.php');&nbsp; &nbsp; &nbsp; &nbsp; const data = await response.text();&nbsp; &nbsp; &nbsp; &nbsp; const dataObject = JSON.parse(data);&nbsp; &nbsp; &nbsp; &nbsp; console.log(dataObject);&nbsp; &nbsp; &nbsp; let li = `<tr><th></th> <td> </td> <th></th></tr>`;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; dataObject.forEach(user => {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; li += `<tr>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>${user.email} </td>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>${user.message}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>`;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;&nbsp; &nbsp;&nbsp; &nbsp; document.getElementById("chat").innerHTML = li;&nbsp;&nbsp;}&nbsp; &nbsp;setInterval(updateDisplay, 1000);
打开App,查看更多内容
随时随地看视频慕课网APP