如何格式化PHP的JS对象数组?

时间:2020-01-17 07:36:31

标签: javascript php ajax

我有这个HTML表单,其中将每一行作为对象推送到数组中,并将其发送给PHP进行处理。

我设法获得响应的ID,但同时也出现 错误 Undefined offset:1 and Trying to get property of 'id' of non-object

我不太明白为什么。我知道当对象中有不匹配的键时会出现第一个错误,但是在这种情况下,我没有任何键。我认为这可能是由于js和PHP之间对象数组的结构差异而发生的。感谢您的帮助。

JavaScript和AJAX

      $(function(){
          $(".checkBoxClass").on("click", function() {
              invoices = [];
              $("table > tbody > tr").each(function () {
                  var $tr = $(this);
                  if ($tr.find(".checkBoxClass").is(":checked")) {
                      invoices.push({
                          id: Number($tr.find("#id").text()),
                          name: $tr.find("#adSoyad").text(),
                          cariKodu: $tr.find("#cariKodu").text(),
                          adres: $tr.find("#adres").text(),
                          il: $tr.find("#il").text(),
                          ilce: $tr.find("#ilce").text()
                      });
                  }
              });
                  console.clear();
              console.log(JSON.stringify(invoices));
              });
          });

          function sendInvoice(){
              var invoicesArray = JSON.stringify( invoices );
              $.ajax({
                  type: "POST",
                  url: "invoice.php",
                  //contentType: 'application/json',
                  data: {data : invoicesArray}, 
                  success: function(respond){
                      alert(respond);
                  }
              });
          }

服务器代码PHP

    $data = json_decode(stripslashes($_POST['data']));

    for($i=0; $i<=count($data); $i++){
        echo($data[$i]->id);
        echo"\n";
    }

0 个答案:

没有答案