javascript - 使用 PHP 的 for-each 循环访问嵌套对象的 JSON 数组的所有项目
问题描述
我已经用 HTML 构建了一个表单,并将用户使用 JSON.stringify() 和 XMLHttpRequest() 输入的所有数据发送到 PHP 文件并将其存储在一个变量中。现在我想在网页上显示所有这些信息,我想为此使用 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>
这是作为 Request PayLoad 发送的 JSON 对象,正如我在开发人员工具的网络选项卡中看到的那样:-
[{"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);
}
}
关于您的代码的一些说明:
- 您的 PHP 响应以 -> 开始,
$output= "<ul>";
但以$output.="</div>";
-> 更改<ul>
为<div>
. - 正如 aXuser26 所指出的,您的服务器端代码是错误的,
[d]
应该删除。我认为您在客户端将 JSON 变量标记为“d”时感到困惑,但变量名称不会传递给服务器。 - 您的变量中缺少一个“q”
$reuestPayload
(尽管这不是问题^^)。
推荐阅读
- ffmpeg - 无效的音频流。只需要一个 MP3 音频流
- java - 为什么 log4j2 的 ${web:rootDir} Web 查找会导致在 weblogic 12c 中的部署出现问题?
- python - 使用 xlsx writer 将图像从 sqlite 导出到 Excel 文件
- docker - 在 docker 中,为什么我在构建图像时看不到任何中间图像?
- c# - 如何删除从`ListView`生成的`ListViewSubItem`表单PDF?
- php - dns_get_record() 没有返回所有记录
- arrays - 如何使用带有_id数组的动态集合的聚合来获取数据
- python - 如何获取函数是函数的变量列表?
- javascript - react-router 的工作方式和 href 标签的工作方式之间的区别?
- c - 为什么 fopen 文件夹失败?