我正在嘗試使用 Javasript fetch API 從資料庫中獲取和提醒 id和name記錄。
我的問題是沒有任何警報,因為警報是空的。
我認為這行代碼有問題
response.json().then(
. 這是資料庫回傳的 json 示例
[{"id":"5","name":"moore Lizzy"}]
這是獲取 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);
uj5u.com熱心網友回復:
上面的語法不太正確。您將 the.next()直接鏈接到response.json()- 即response.json().then(它應該更像以下(稍微縮寫)的地方,其中 the系結到回傳 JSON.next()的整個前一個部分next()
fetch( '/record/rec.php' )
.then( r=>r.json() )
.then( json=>{
Object.keys( json ).forEach(k=>{
alert( `${k} - ${json[k]}` )
})
})
uj5u.com熱心網友回復:
在此處添加回傳代碼行也解決了該問題。最后,我還確保代碼中沒有空白。
return response.json().then(
uj5u.com熱心網友回復:
你也可以這樣做:
fetch('https://jsonplaceholder.typicode.com/posts', {"method": "GET",})
.then(async (response) => {
const data = await response.json();
console.log("data: ", data)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486791.html
標籤:javascript php
下一篇:錯誤:ENOENT:沒有這樣的檔案或目錄,打開'C:\Users\username\Desktop\vue-tailwind-naive\tailwind.config.js
