簡體   English   中英

使用 PHP 的 for-each 循環訪問嵌套對象數組 JSON 的所有項目

[英]Accessing all the items of JSON array of nested objects using PHP's for-each loop

我在 HTML 中構建了一個表單,並將用戶使用 JSON.stringify() 和 XMLHttpRequest() 輸入的所有數據發送到 PHP 文件並存儲在變量中。 現在我想在 web 頁面上顯示所有這些信息,我想為此使用 for-each 循環,但我不明白我應該如何在循環中傳遞參數並訪問它們。

這是 HTML 代碼:-

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="styling.css">
</head>
<body>
    <div class="container">
        <h1>Popup for adding/editing Expertise details</h1>
        <a href="#" class="button">Add/Edit</a>
    </div>

    <div class="popup">
        <div class="popup-content">

            <div class = "register">
      <form method="post" id="register" action="">

          <label for="area"> Expertise Area: </label><br>
          <input type="text" name="area" id="area"
          placeholder="Enter your Expertise Area"><br><br>
          <label> Experience: </label><br>
          <label for="mnth">No. of months:</label>
          <input type="number" id="mnth" name="mnth" min="1" max="11">
          <label for="yr">No. of years:</label>
          <input type="number" id="yr" name="yr" min="1" max="50"><br><br>
          <label> Rates </label><br><br>
          <label for="remote"> Remote: </label><br>
          <select id="remote_option">
            <option>per hour</option>
            <option>per topic</option>
            <option>per chapter</option>
          </select>
          <label for="remote_amt">Amount in Rs.:</label>
          <input type="number" id="remote_amt" name="remote_amt">
          <label for="center"> Center: </label><br>
          <select id="center_option">
            <option>per week</option>option>
            <option>per month</option>option>
          </select>
          <label for="center_amt">Amount in Rs.:</label>
          <input type="number" id="center_amt" name="center_amt">
          <label for="learner"> Learner's Place: </label><br>
          <select id="learner_option">
            <option>per class</option>option>
            <option>per hour</option>option>
          </select>
          <label for="learner_amt">Amount in Rs.:</label>
          <input type="number" id="learner_amt" name="learner_amt"><br>
          <label for="my"> My Place: </label><br>
          <select id="my_option">
            <option>per class</option>option>
            <option>per hour</option>option>
          </select>

          <label for="my_amt">Amount in Rs.:</label>
          <input type="number" id="my_amt" name="my_amt"><br><br>
          <div class="button">
            <button id="btn">Submit</button>
          </div>
          <img src="close.png" class="close" alt="Close">
      </form>
      </div>

        </div>
    </div>
  <script>
    document.querySelector(".button").addEventListener("click", function(){
       document.querySelector(".popup").style.display = "flex";});
  document.querySelector(".close").addEventListener("click", function(){
       document.querySelector(".popup").style.display="none";});
  </script>

  <script>
    let data=[];
    const addData=(ev)=>{
      ev.preventDefault();
      let d={
        exp_area: document.getElementById('area').value,
        exp_yrs: document.getElementById('mnth').value,
        exp_mnth: document.getElementById('yr').value,
        rates: [
          {
            mode: 'remote',
            charge: document.getElementById('remote_amt').value,
            unit: document.getElementById('remote_option').value
          },
          {
            mode: 'center',
            charge: document.getElementById('center_amt').value,
            unit: document.getElementById('center_option').value
          },
          {
            mode: 'learner',
            charge: document.getElementById('learner_amt').value,
            unit: document.getElementById('learner_option').value
          },
          {
            mode: 'my',
            charge: document.getElementById('my_amt').value,
            unit: document.getElementById('my_option').value
          }
        ]
      }
      data.push(d);
      document.forms[0].reset();

      const JsonString = JSON.stringify(data);
      console.log(JsonString);

      const xhr = new XMLHttpRequest();

      xhr.open("POST","receive.php");
      xhr.setRequestHeader("Content-Type","application/json");
      xhr.send(JsonString);
    }

    document.addEventListener('DOMContentLoaded',()=>{
      document.getElementById('btn').addEventListener('click',addData);
    });
  </script>
  <script type="text/javascript" src="submit.js"></script>
</body>
</html>

這里是 JSON object,它作為 Request PayLoad 發送,正如我在開發人員工具的網絡選項卡中看到的那樣:-

[{"exp_area":"gfds","exp_yrs":"","exp_mnth":"","rates":[{"mode":"remote","charge":"","unit":"per hour"},{"mode":"center","charge":"","unit":"per week"},{"mode":"learner","charge":"","unit":"per class"},{"mode":"my","charge":"","unit":"per class"}]}]

這就是我在 PHP 文件中嘗試的內容:-

<?php

$reuestPayload = file_get_contents("php://input");
$arr = json_decode($reuestPayload,true);
var_dump($arr);

$output= "<ul>";
foreach ($arr[d] as $value) {
    $output .= "<h4>".$d['exp_area']."</h4>";
    $output .= "<h4>".$d['exp_yrs']."</h4>";
    $output .= "<h4>".$d['exp_mnth']."</h4>";
    $output .= "<h4>".$d['rates']['mode']."</h4>";
    $output .= "<h4>".$d['rates']['charge']."</h4>";
    $output .= "<h4>".$d['rates']['unit']."</h4>";

}
$output.="</div>";
?>

請求有效載荷:

這是請求有效負載屏幕截圖

由於數據是異步發送和接收的,因此在執行提交例程后不會刷新頁面。 您可能會做的是從后端返回 HTML 並將其添加到特定元素作為 XHR 響應的一部分。

添加一個結果元素以顯示服務器響應:

<div id="result"><h3>Result:</h3></div> 

修改你的 JS 例程:

在你的xhr.open()行之前添加這個:

xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        document.getElementById('result').innerHTML += (xhr.responseText);
    }
}

關於您的代碼的一些說明:

  1. 你開始你的 PHP 響應$output= "<ul>"; 但以$output.="</div>"; -> 將<ul>更改為<div>
  2. 正如 aXuser26 所指出的,您的服務器端代碼是錯誤的,應該刪除[d] 我認為您在客戶端將 JSON 變量標記為“d”時感到困惑,但變量名稱不會傳遞給服務器。
  3. 您的變量$reuestPayload中缺少一個“q”(盡管這不是問題^^)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM