我正在 jQuery 中创建一个对象数组。
var selected_tests = $("#selected_tests").find("tr");
jsonLab = [];
$.each(selected_tests, function() {
jsonLab.push({
test: ($(this).children()).eq(0).text(),
amount: ($(this).children()).eq(1).text()
});
});
我通过
将此数组发布到 PHP 文件$('<input type="hidden" name="jsonLab"/>').val(jsonLab).appendTo('#bill_print');
$("#bill_print").submit();
在我的 PHP 文件中
if(isset($_POST['jsonLab']))
{
$lab = json_decode($_POST['jsonLab'],true);
foreach ($lab as $key => $value) {
echo $value["test"] . ", " . $value["amount"] . "<br>";
}
}
我使用 foreach
的方式似乎有一些错误,或者它可能是格式不正确的 JSON,PHP 没有对其进行解码。我不想使用 AJAX 进行提交。
最佳答案
问题出在这个调用上:
.val(jsonLab)
jsonLab
是 JS 中保存的对象数组。因此,将其设置为 jQuery 对象的 val()
将意味着在其上调用 toString()
。其结果是 [object Object]
。这是发送到您的 PHP 逻辑的内容,因此是错误。
要解决此问题,您需要在将其设置为文本字段的值时手动将 JSON 字符串化:
$('<input type="hidden" name="jsonLab" />').val(JSON.stringify(jsonLab)).appendTo('#bill_print');
另请注意,您可以对 #selected_tests tr
元素使用单个 map()
调用,而不是选择然后推送到显式实例化的数组:
var jsonLab = $("#selected_tests tr").map(function() {
return {
test: $(this).children().eq(0).text(),
amount: $(this).children().eq(1).text()
};
}).get();
关于javascript - 遍历 PHP 中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268158/