【发布时间】:2019-05-14 03:46:45
【问题描述】:
我正在尝试将 JSON 数组从 Javascript 发送到 Php 以插入到数据库中。我可以看到控制台日志上显示的数组,但我不知道如何在 Php 中接收它。 JSON 数组将在我的级联选项列表中使用,其中所选值将显示在表格中。这就是函数 SaveData 将获取要在 Php 中发送的值的地方。
var ModelArray = {
"Mammals": {
"Dog": {
"Dog Food": ["Milk"]
},
"Cat": {
"Cat food": ["Milk"]
},
"Tiger": {
"Meat": ["Water"]
},
"Monkey": {
"Banana": ["Water"]
}
},
"Reptiles": {
"Snake": {
"Rat": ["None"]
},
"Turtle": {
"Plant": ["Water"]
},
"Lizard": {
"Insects": ["None"]
},
"Crocodile": {
"Meat": ["Water"]
}
}
}
function SaveData() {
var DataList = [];
var table = document.getElementById("bod");
var rowLength = table.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = table.rows.item(i).cells;
//gets amount of cells of current row
//var cellLength = oCells.length-2;
//loops through each cell in current row
var item = [];
item["destination"] = oCells.item(0).innerHTML;
item["criteria"] = oCells.item(1).innerHTML;
item["material"] = oCells.item(2).innerHTML;
DataList.push(item)
request = new XMLHttpRequest()
request.open("POST", "DOM_SAVE.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(DataList);
}
console.log(DataList);
}
PHP 代码
<?php
$DataList = file_get_contents('php://input');
echo '$DataList';
?>
【问题讨论】:
-
请在您的问题中发布您的 php 代码。
-
DOM_SAVE.php长什么样子? -
不能直接发送
DataList,需要用JSON.stringify()序列化。 -
代码更新请看
-
我会序列化整个 DataList 数组吗? @Barmar
标签: javascript php html json xmlhttprequest