通过 POST 将数组从 Javascript 传递到 PHP

Passing array from Javascript to PHP via POST

本文关键字:PHP Javascript POST 数组 通过      更新时间:2023-09-26

我已经查看了有关此问题的其他几个建议,但由于某种原因,我的数据没有发布。 这是我代码的相关部分:

<input type="button" id="map_submit" value="Map Selection" />
<?php var_dump($_POST); ?>  // display the posted variables

<script type="text/javascript">
    $(document).ready(function(){
        $('#map_submit').click(function(){
            /*  this part is from the slickgrid plugin, in which
             *  selectedData is an array that I want to post to the page
             *  and read via php
             */
            var selectedData = [], selectedIndexes;
            selectedIndexes = grid.getSelectedRows();
            jQuery.each(selectedIndexes, function (index, value) {
                 selectedData.push(grid.getData()[value]);
            });
            $.post("mapper.php", {dataArray: selectedData});
        });
    });
</script>

我从其他问题中看到的情况来看,$.post应该有效。 但是,当我单击按钮时,var_dump中没有显示任何内容。 作为健全性检查,如果我将其添加到 javascript 中:

for (var i = 0; i < selectedData.length; i++) {
     document.write(selectedData[i].questionID + "<br />");
}

它将打印我在网格中选择的questionID值(当然是打印到新的空白页)。

$.post("mapper.php", {dataArray: selectedData});

这条线很好。 我不知道为什么每个人都建议使用JSON,因为这里没有必要。 您可以正常地 POST 对象/数组而不使用 JSON。

注意:这不会重新加载页面。 它将通过 AJAX 发布到mapper.php,因此不会在页面上的任何地方看到任何内容。 您需要查看开发工具以查看 AJAX 调用返回的内容。

或者,您可以检查 POST 返回的数据。

$.post("mapper.php", {dataArray: selectedData}, function(data){
    console.log(data); // check your console, you should see some output
});

您必须在发布前序列化对象,然后在服务器上反序列化(大概在 PHP 中),然后才能使用它。

下面的示例(需要 json2.js):

<script type="text/javascript">
    $(document).ready(function(){
        $('#map_submit').click(function(){
            /*  this part is from the slickgrid plugin, in which
             *  selectedData is an array that I want to post to the page
             *  and read via php
             */
            var selectedData = [], selectedIndexes;
            selectedIndexes = grid.getSelectedRows();
            jQuery.each(selectedIndexes, function (index, value) {
                 selectedData.push(grid.getData()[value]);
            });
            $.post("mapper.php", JSON.stringify({dataArray: selectedData}));
        });
    });
</script>
<input type="button" id="map_submit" value="Map Selection" />
<?php var_dump(json_decode($_POST, true)); ?>  // display the posted variables