我正在嘗試使用 Javasript fetch API 從數(shù)據(jù)庫(kù)中獲取警報(bào) ID 和名稱記錄。
我的問題是,由于警報(bào)為空,因此沒有任何警報(bào)。
我認(rèn)為這行代碼有問題
response.json().then(
。 這是數(shù)據(jù)庫(kù)返回的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);
在此處的代碼行中添加return也解決了該問題。最后,我還確保代碼中沒有空白。
return response.json().then(
上面的語(yǔ)法不太正確。您將 .next()
直接鏈接到 response.json()
- 即 response.json().then(
,它應(yīng)該在哪里更像下面的(稍微縮寫),其中 .next()
綁定到返回 JSON 的整個(gè)前一個(gè) next()
部分
fetch( '/record/rec.php' ) .then( r=>r.json() ) .then( json=>{ Object.keys( json ).forEach(k=>{ alert( `${k} - ${json[k]}` ) }) })