使用PHP Ajax在POST上检索数组数据

时间:2017-10-18 09:55:10

标签: php json ajax

我需要提交一个JSON对象数组

[{"id":"321","position":"2"},{"id":"359","position":"3"}]

所以我试过

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': _token
    }
});

table.on( 'row-reorder', function ( e, diff, edit ) {
    var myArray = [];
    for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
      var rowData = table.row( diff[i].node ).data();
      myArray.push({
          id: rowData.id,           // record id from datatable
          position: diff[i].newData     // new position
      });
    }
   var jsonString = JSON.stringify(myArray);
   //jsonString output an array as the one above
   $.ajax({
            url     : "/requests/setOrder.php",
            type    : 'POST',
            data    : jsonString,
            dataType: 'json',
            success : function ( json ) 
            {
                $('#example23').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                    // handle json response
                });
            }
        });
  });

setOrder.php我想dump我的数组,所以我尝试了:

$result = json_encode($_POST);
var_dump($result);

数组是否正确提交,为什么响应为空?

2 个答案:

答案 0 :(得分:1)

首先你需要删除var jsonString = JSON.stringify(myArray); - 数据不应该在“数据”字段中以“json”的形式发送 - jQuery为你做了

在发送数据之前,您应该将其分配给变量:

data    : {data: myArray}

同样在后端,您应该使用$result = json_decode($_POST['data']);

您的完整代码应为:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': _token
    }
});

table.on( 'row-reorder', function ( e, diff, edit ) {
    var myArray = [];
    for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
      var rowData = table.row( diff[i].node ).data();
      myArray.push({
          id: rowData.id,           // record id from datatable
          position: diff[i].newData     // new position
      });
    }
   //jsonString output an array as the one above
   $.ajax({
            url     : "/requests/setOrder.php",
            type    : 'POST',
            data    : {data: myArray},
            dataType: 'json',
            success : function ( json ) 
            {
                $('#example23').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                    // handle json response
                });
            }
        });
  });

并在PHP中: 如果你在发送之前json.stringify你的数据,你需要在这里解码它。但是,发送到服务器时不需要发送JSON。但是,您将收到JSON作为回报。

$result = $_POST['data'];
var_dump($result);

答案 1 :(得分:0)

首先在ajax中设置数据,如下所示:

data    :{jsonString: jsonString},

然后在你的php文件中将$ _post设置为像

这样的变量
$myVar=$_POST['jsonString'];

你得到了那样的反应

相关问题