PHP返回空POST数组

PHP returning empty POST array

本文关键字:数组 POST 返回 PHP      更新时间:2023-09-26

JavaScript jQuery post:

var animals = {
    animalsArray: [],
    tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
    animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
    console.log(response);
}, "json");
PHP处理器:

echo json_encode(print_r($_POST, true));
// Array
// (
// )

为什么数组是空的?我张贴数据,但响应返回一个空数组。

您将数据编码为JSON,这不是PHP原生处理表单提交的格式。

移除var sendMe = JSON.stringify(animals);,将animals传给$.post,而不是sendMe。jQuery将使用HTML表单和PHP支持的标准格式之一对其进行编码。

关于如何获取原始请求正文,请参见这个问题。


:

echo json_encode(print_r($_POST, true));

json_encodeprint_r都是接受数据结构并将其表示为字符串的函数。使用其中一个,而不是两个。