2

如何在 jquery 中将我的对象数组序列化为 php?

我有这个:

数组结构的控制台日志

我需要在 php 中发送这个数组jQuery(vetDespesas)来创建我的 sql 查询。

我尝试使用 dump php serializeunserialize但它不起作用。

我在 jQuery 中使用它:

   // this = my Form html

    var dataSend = $(this).serializeArray(); // other datas...

    dataSend.push({name:'moeda',value:moeda});
    dataSend.push({name:'moedaCotacao',value:moedaCotacao});
    **dataSend.push({name:'vetDespesas',value:vetDespesas});** object array

在php中,我该如何编写代码?

$requisitadopor = $_POST['requisitadopor'];
$autorizadopor = $_POST['autorizadopor'];
$departamento = $_POST['departamento'];
$unidade = $_POST['unidade'];

var_dump($_POST['vetDespesas']);  // doesn't work =/ (array of objects)


vetDespesas = JSON.stringify(vetDespesas);

我使用 php:

    $a = json_decode($_POST['vetDespesas']);
    var_dump($a[0]);

我的 chrome 控制台打印:

对象stdClass)[ 2 ] 公共'dataDespesa'=>字符串'15/12/2015' (长度=10) 公共'descDespesa'=>字符串'teste1' (长度=6) 公共'budgetDespesa'=>字符串'001 001 0E2R' (长度=12) 公共'valorDespesa'=>字符串'2133.33' (长度=7)

我怎样才能访问这些数据?

4

1 回答 1

1

在将其发送到 PHP 之前,您应该将其转换为 JSON 字符串:

vetDespesas = JSON.stringify(vetDespesas);

要在 PHP 代码中获取对象,您应该使用json_decode()

$my_object = json_decode($_POST['vetDespesas']);

您可以使用访问object(stdClass)属性->,例如:

echo $my_object->dataDespesa;
echo $my_object->budgetDespesa;

希望这可以帮助。

于 2015-12-15T23:46:06.233 回答