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

时间:2012-06-21 14:26:59

标签: php javascript jquery .post

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

<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值(当然是新的空白页面)。

2 个答案:

答案 0 :(得分:2)

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

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

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

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

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

答案 1 :(得分:1)

您必须先预先发布对象,然后在服务器上进行反序列化(可能是在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
相关问题