我在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中保存的对象的数组。因此,将其设置val()
为jQuery对象的表示将对其toString()
进行调用。结果是[object Object]
。这就是发送到您的PHP逻辑的内容,因此是错误。
要解决此问题,您需要在将JSON设置为文本字段的值时手动对其进行字符串化:
$('<input type="hidden" name="jsonLab" />').val(JSON.stringify(jsonLab)).appendTo('#bill_print');
还要注意,您可以map()
对#selected_tests tr
元素使用单个调用,而不是选择然后推送到显式实例化的数组:
var jsonLab = $("#selected_tests tr").map(function() {
return {
test: $(this).children().eq(0).text(),
amount: $(this).children().eq(1).text()
};
}).get();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句