我使用 bootstrap 5 制作了一個網站,其中大部分是 jQuery Ajax。這些卡片是在頁面加載時使用 PHP 腳本加載的,這就像一個魅力。但是我已經到了我希望選擇輸入起作用的地方。當你點擊它時,你可以選擇是否要將排序更改為 creation_date、modified_date 或默認排序(按 id 排序)。
這是它在視覺上的樣子。
我正在使用 PHP 創建一個陣列,然后使用 json_encode 在 jquery 上從前端訪問它。
這是我正在使用的代碼:
while($row = mysqli_fetch_array($sql)) {
$i ;
$id = $row['id']; // Get id of card.
$r = $row['tittel']; // Get title value of card.
$o = $row['opprettet']; // Get value for 'created' date for the card
// I use this function to loop through all the values and put them in an array.
for ($x = 1; $x <= 2; $x ){
$jsonarray['card'] = array(
'id' => $x,
'title' => $r,
'opprettet' => $o,
);
}
echo json_encode($jsonarray, JSON_UNESCAPED_SLASHES);
}
上面的代碼輸出到這個 json:
{
"card":{
"id":2,
"title":"Pizza",
"opprettet":"15/10/2022 02:50"
}
}{
"card":{
"id":2,
"title":"Spaghetti a la capriadgadg",
"opprettet":"15/10/2022 05:08"
}
}{
"card":{
"id":2,
"title":"test ingrediens",
"opprettet":"15/10/2022 13:14"
}
}{
"card":{
"id":2,
"title":"Middag for den mette, eller en enda mindre middag for 2.",
"opprettet":"16/10/2022 13:51"
}
}{
"card":{
"id":2,
"title":"Fruktfat for den feite",
"opprettet":"16/10/2022 13:55"
}
}
我已經嘗試過來自其他堆疊溢位文章、reddit 和其他網站的示例,但他們都沒有像我一樣在一段時間內這樣做。我怎樣才能使它對前端的 javascript 可讀?一旦我的 PHP 代碼沒問題,我就可以讓它在前端可讀,并按計劃在卡片中顯示 json 的內容。
uj5u.com熱心網友回復:
我建議您將所有物件放在一個陣列中,并在獲取所有行后進行編碼。像這樣的東西(調整你的代碼):
$json = [];
while($row = mysqli_fetch_array($sql)) {
$i ;
$id = $row['id']; // Get id of card.
$r = $row['tittel']; // Get title value of card.
$o = $row['opprettet']; // Get value for 'created' date for the card
// I use this function to loop through all the values and put them in an array.
for ($x = 1; $x <= 2; $x ){
$json[] = ["card" => [
'id' => $x,
'title' => $r,
'opprettet' => $o,
]];
}
}
echo json_encode($json, JSON_UNESCAPED_SLASHES);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515200.html
下一篇:如何在輸入值后向輸入添加文本
