[英]Passing array from Javascript to PHP via 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
值(当然是新的空白页面)。
$.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
});
您必须先预先发布对象,然后在服务器上进行反序列化(可能是在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.