我正在尝试使用 Javasript fetch API 从数据库中获取警报 ID 和名称记录。
我的问题是,由于警报为空,因此没有任何警报。
我认为这行代码有问题
response.json().then(
。 这是数据库返回的json示例
[{"id":"5","name":"moore Lizzy"}]
这里是 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);
});
}
)
})
这是 php 代码
//connect db
$id = "5";
$name = "More Lizy";
$result_arr[] = array(
"id" => $id,
"name" => $name
);
echo json_encode($result_arr); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在此处的代码行中添加return也解决了该问题。最后,我还确保代码中没有空白。
上面的语法不太正确。您将
.next()直接链接到response.json()- 即response.json().then(,它应该在哪里更像下面的(稍微缩写),其中.next()绑定到返回 JSON 的整个前一个next()部分fetch( '/record/rec.php' ) .then( r=>r.json() ) .then( json=>{ Object.keys( json ).forEach(k=>{ alert( `${k} - ${json[k]}` ) }) })