我正在為學校建立一個簡單的網頁。可悲的是我遇到了幾個問題。我使用帶有 XAMPP 的 Apache 網路服務器。
我得到了一個 JSON 檔案,如:
{
"lose":[
{
"Zustand":"geschlossen",
"Losnummer":1,
"Gewinnklasse":"A",
"Preis":10
},
{
"Zustand":"geschlossen",
"Losnummer":2,
"Gewinnklasse":"B",
"Preis":20
},
這個檔案也在我的網路服務器上。我想用 XHTML 請求加載這個檔案,然后想把這個 JSON 檔案的幾個部分列印成 HTML/PHP 代碼。我看了很多 YouTube 視頻,但沒有找到適合我的方法。我設法通過 XHTML 加載了 JSON 檔案,并且能夠用 HTML 列印它,但它始終是所謂的“responseText”中的整個 JSON,這對我來說基本上是一個大字串。我在這方面相當新,如果我把事情搞砸了,很抱歉。
所以 TLDR:在網頁中加載 JSON 檔案,在幾個 HTML div 標簽中列印它的單個部分。我允許使用 html、php、js。
uj5u.com熱心網友回復:
像這樣的東西:
<?php
$json =
'
{
"lose": [
{
"Zustand":"geschlossen",
"Losnummer":1,
"Gewinnklasse":"A",
"Preis":10
},
{
"Zustand":"geschlossen",
"Losnummer":2,
"Gewinnklasse":"B",
"Preis":20
}]
}
';
$arr = json_decode($json, true);
echo "<table border='1'>";
foreach($arr["lose"] as $single) {
echo "<tr>";
echo "<td>".$single['Zustand']."</td>";
echo "<td>".$single['Losnummer']."</td>";
echo "</tr>";
}
echo "</table>";
uj5u.com熱心網友回復:
在 JS 中,您可以使用內置JSON.parse()方法。
https://www.w3schools.com/Js/js_json_parse.asp
然后,您可以作為一等公民訪問該資料結構中的各個元素。
使用您的示例,這是一個最小的作業示例:
let dataString = `
{
"lose":[
{
"Zustand":"geschlossen",
"Losnummer":1,
"Gewinnklasse":"A",
"Preis":10
},
{
"Zustand":"geschlossen",
"Losnummer":2,
"Gewinnklasse":"B",
"Preis":20
}
]
}
`
let data = JSON.parse(dataString);
// If we log out data, it will simply print everything
console.log(data);
// This will access the first element of the array
console.log(data.lose[0]);
// To iterate through the entire 'LOSE' array
data.lose.forEach(element => {
// Since we're in the middle of the array, we can now access individual properties
console.log(element.Zustand);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357454.html
標籤:javascript php html json
