我有一个表,有些<td>有一个数据,但不是全部。在一个按钮上单击我运行jquery函数,它检查每个<td>并在数据存在的地方获取数据。
之后,数据被传递到php文件并插入到我的数据库中。一切都很好。

function insert_data() {
  if(confirm("\nAre you sure?.\n")) {
    $("#myTable td").each( function() {
      var worker = $(this).attr("id");
      var quarter = $(this).attr("title");
      var station = $(this).attr("name");
      var type = $(this).attr("class");
      $.post({ url: "insert_data.php", data: {worker:worker, quarter:quarter, station:station, type:type} });
    });
  }
  else { return false; }
}

我想知道是否有一种方法可以像传递一个包一样传递数据,而不是用ajax为每个<td>调用php?我在这里和其他网站上查看了至少几十篇不同的文章,似乎json经常用于此目的。
我从未使用过json,在尝试了几天不同的方法之后,仍然无法找出我做错了什么。我会感谢你的帮助。
我只需要将数据从表传递到php文件(并在其中解压缩)。我不需要在html页面上同时显示它。
以下是其中一个不起作用的版本:
JS公司:
function insert_data() {
  if(confirm("\nAre you sure?.\n")) {
    var myArray = []; // var to store all records for json data transfer
    $("#myTable td").each( function() {
      var worker = $(this).attr("id");
      var quarter = $(this).attr("title");
      var station = $(this).attr("name");
      var type = $(this).attr("class");
      var record = {worker:worker, quarter:quarter, station:station, type:type}; // sd - short for schedule data
      myArray.push(record); // add every record to same array
    });
      console.log(myArray);
      $.post({ url: "insert_data.php", data: {myArray: myArray }, success: function(data){ alert('Items added'); }, error: function(e){ console.log(e.message); } });
  }
  else { return false; }
}

在控制台中,我看到以下数据(看起来数据正在毫无问题地添加到阵列中):
(4) [{...}, {...}, {...}, {...}]
0: {worker: "556", quarter: "1", station: "abc_15", type: "rework"}
1: {worker: "147", quarter: "2", station: "abc_37", type: "rework"}
2: {worker: "345", quarter: "3", station: "abc_15", type: "rework"}
3: {worker: "12", quarter: "4", station: "abc_15", type: "rework"}

菲律宾比索:
  $mySchedule = array();
  $mySchedule[] = $_POST["myArray"];  // get the json array
  var_dump($mySchedule);
  foreach ($mySchedule as $sched) {
    $worker = $sched['worker']; // or: $sched->worker; - doesn't change the result
    $quarter = $sched['quarter'];
    $station = $sched['station'];
    $type = $sched['type'];
    // code to insert data into my DB - works fine when I pass data one by one instead of array
  }

HTML格式:
我还将此脚本添加到带有表的页面中:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-json/2.6.0/jquery.json.min.js"></script>

我不确定是否需要。
--
感觉问题在于我如何“解包”数组。但我不确定…我试着遵循我在这里能找到的所有建议,但也许我只是错过了一些真正重要的东西。
我试过:
$mySchedule[] = json_decode($_POST["myArray"]); // in insert_data.php

data:  { json: JSON.stringify(myArray) } // in jQuery function

还有其他一些建议…

最佳答案

更新
我从我的一所大学得到了一些帮助。因此,jquery代码保持不变。php代码有几个小改动,现在运行良好。php中的更改:

$mySchedule = $_POST["myArray"];  // get the json array

而不是:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"];  // get the json array

就这样。非常感谢您的帮助和建议。我希望这个例子对其他人有帮助。

关于php - 一组将数据从jQuery传递到PHP文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54876267/

10-14 13:34
查看更多