[英]How to parse nested JSON sent via AJAX in PHP
Say I have this AJAX sent via jQuery to a PHP server假设我有这个 AJAX 通过 jQuery 发送到 PHP 服务器
$.ajax({
url: woocommerce_admin_meta_boxes.ajax_url,
data: data,
type: 'POST',
success: function (res) {
if (res.success) {
location.reload();
}
}
});
and data
looks like this和
data
看起来像这样
data = {
order_id: woocommerce_admin_meta_boxes.post_id,
order_items : [
{
order_item_id: 69420,
amount: 420
},
{
order_item_id: 42069,
amount: 69
}
]
};
What I have found out is by using PHP's $_POST
, I can access the order id like this我发现是通过使用 PHP 的
$_POST
,我可以像这样访问订单 ID
$order_id = $_POST['order_id'];
However, I am not sure of how I can access stuff inside order_items
from data
.但是,我不确定如何从
data
访问order_items
内容。 From what I've seen in this stackoverflow post , there's a PHP function called json_decode()
, but I'm not so sure of how to use this together with AJAX or $_POST
.从我在这个 stackoverflow 帖子中看到的,有一个名为
json_decode()
的 PHP 函数,但我不太确定如何将它与 AJAX 或$_POST
一起使用。
$.ajax()
doesn't use JSON encoding, it sends URL-encoded format, so there's no need to use json_decode()
. $.ajax()
不使用 JSON 编码,它发送 URL 编码格式,因此不需要使用json_decode()
。
To access the nested data, just use ordinary array accessing in the $_POST
variable.要访问嵌套数据,只需在
$_POST
变量中使用普通数组访问即可。
foreach ($_POST['order_items'] as $item) {
echo "Item ID: " . $item['order_item_id'] . "<br>";
echo "Amount: " . $item['amount'] . "<br>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.