从Javascript发送JSON数组并在php

时间:2018-12-12 23:58:02

标签: javascript php html json xmlhttprequest

我试图将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';

  ?>

1 个答案:

答案 0 :(得分:0)

您需要序列化DataList数组:

request.send(JSON.stringify(DataList));

您不应该在for循环内发送请求。在循环中构造整个DataList,然后在最后发送AJAX请求。

如果要发送具有命名属性的对象数组,则不应使用数组作为元素。更改

var item = [];

var item = {};

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)


  }
  var request = new XMLHttpRequest()
  request.open("POST", "DOM_SAVE.php", true)
  request.setRequestHeader("Content-type", "application/json")
  request.send(JSON.stringify(DataList));

  console.log(DataList);
}

在PHP中,您需要对其进行解码:

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