[英]Loop over array of objects in PHP
我在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.