我正在尝试将数组从 .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,然后 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 };
}
谢谢
最佳答案
嗯,你不能在 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
即可获得长度。
关于javascript - 数组从js到php,计算数组长度出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587257/