Доступ ко всем элементам массива JSON вложенных объектов с использованием PHP для каждого цикла - PullRequest
0 голосов
/ 07 мая 2020

Я создал форму в HTML и отправил все данные, введенные пользователем, используя JSON .stringify () и XMLHttpRequest (), в файл PHP и сохранил их в переменной. Теперь я хочу отобразить всю эту информацию на веб-странице, для которой я хочу использовать для каждого l oop, но я не понимаю, как именно мне передать параметры в l oop и получить к ним доступ.

Вот код 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, который отправляется как 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>";
?>

Запросить полезную нагрузку:

Here is the request payload screenshot

1 Ответ

0 голосов
/ 07 мая 2020

Поскольку данные отправляются и принимаются асинхронно, страница не будет обновляться после выполнения процедуры отправки. Что вы можете сделать, так это вернуть HTML из своего бэкэнда и добавить это к указанному элементу c как часть ответа 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. В вашей переменной отсутствует "q" $reuestPayload (хотя это не проблема ^^).
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...