我正在尝试将我的.js文件中的数组传递给php文件。 该数组在js中如下所示:
theBlock[0 - 79] with the values color, x and y. So for example
theBlock[10].color or
theBlock[79].x
使用以下脚本传递此数据:
$.ajax({
type: 'POST',
url: 'insert.php',
data: $(theBlock).serialize()
}).done(function (data) {
console.log(data);
}).fail(function () {
alert("Failed");
});
php正在关注:
$newData = $_POST;
echo count($newData["theBlock"]) . "\n";
现在当调用激活它的函数时,数据应该传递给php,然后将数据发送给我。好吧,它总是把我送回去" 0"。
该数组由以下脚本创建:
var theBlock = [];
for (c = 0; c < 80; c++) {
theBlock.push({color: 0});
}
之后,按以下方式更改数组:
if (ctx.getImageData(xPixel + minX, yPixel + minY, 1, 1).data[3] == 255 && ctx.getImageData(xPixel + minX, yPixel + minY, 1, 1).data[0] == 000) {
id = (xBlock + (yBlock - 1) * 8) - 1;
theBlock[id] = { color: 1, x: xBlock, y: yBlock };
}
由于
答案 0 :(得分:2)
好吧,你不能在javascript变量上使用serialize()。请参阅API文档。 http://api.jquery.com/serialize/
如果要对JSON数组进行编码,请使用JSON.stringify()
,然后使用json_decode()。
$.ajax({
type: 'POST',
url: 'insert.php',
data: { block: JSON.stringify(theBlock) }
}).done(function (data) {
console.log(data);
}).fail(function () {
alert("Failed");
});
并且您不需要将$ _POST分配给变量,只需直接使用它即可。
echo count(json_decode($_POST['block'])) . "\n";
旁注:如果您只是想知道数组长度,那么您不需要PHP来做到这一点。只需theBlock.length
即可获得长度。