繁体   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