How to correctly alert database records using Fetch javascript API and php
P粉898107874
P粉898107874 2024-04-03 23:38:11
0
2
390

I'm trying to get the alert ID and name records from the database using Javasript fetch API.

My problem is that since the alerts are empty, there aren't any alerts.

I think there is something wrong with this line of code

response.json().then(

. This is an example of json returned by the database

[{"id":"5","name":"moore Lizzy"}]

This is the fetch API Javascript

fetch("http://localhost/record/rec.php", {
  "method": "GET",
}).then(
  response => {
    response.json().then(
      data => {
        console.log(data);

        data.forEach((r) => {
          alert(r.id);
          alert(r.name);
        });
      }
    )
  })

This is the php code

//connect db

$id = "5";
$name = "More Lizy";
                
$result_arr[] = array(
"id" => $id,
"name" => $name
);

echo json_encode($result_arr);

P粉898107874
P粉898107874

reply all(2)
P粉478835592

Adding return to the line of code here also solved the problem. Finally, I also made sure there were no whitespace in the code.

return response.json().then(
P粉466290133

The above syntax is not quite correct. You link .next() directly to response.json() - i.e. response.json().then( , where it should be more like below (slightly abbreviated), where .next() is bound to the entire previous next() part

of the returned JSON
fetch( '/record/rec.php' )
    .then( r=>r.json() )
    .then( json=>{
        Object.keys( json ).forEach(k=>{
            alert( `${k} - ${json[k]}` )
        })
    })
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!