【问题标题】:How can I get serializableArray jQuery that contains one array object in php?如何在 php 中获取包含一个数组对象的 serializableArray jQuery?
【发布时间】:2016-03-21 23:18:02
【问题描述】:

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

我有这个:

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

我尝试使用 dump php serialize, unserialize 但它不起作用。

我在 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] public 'dataDespesa' => 字符串 '15/12/2015' (length=10) public 'descDespesa' => 字符串 'teste1' (length=6) public 'budgetDespesa' => 字符串 '001 001 0E2R' (length=12) public 'valorDespesa' => 字符串 '2133.33' (length=7)

如何访问这些数据?

【问题讨论】:

  • 请记住,您可以在 stackoverflow 中添加图像,您不需要为此添加外部页面(这可能会死掉,因此将来会损害问题)。在这种情况下,console.log 的复制粘贴会是更好的选择。此外,请保持文本简洁并针对问题。
  • 感谢 k0pernikus 下一个答案我会做的 =)

标签: javascript php jquery arrays arrayobject


【解决方案1】:

你应该把它变成一个 JSON 字符串,然后再发送给 PHP :

vetDespesas = JSON.stringify(vetDespesas);

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

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

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

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

希望这会有所帮助。

【讨论】:

  • 否 =/ 我使用 var_dump 函数,返回结果是:
    string '[object Object],[object Object],[object Object]' (length=47) 
  • 你在哪里用javascript初始化vetDespesas
  • 我的 vetDespesa 在 javascript 中初始化并且是正确的.. var vetDespesas = criaVetorObjDespesa(); var dataSend = $(this).serializeArray(); dataSend.push({name:'vetDespesas',value:vetDespesas});
  • 我尝试了您的更新,但不起作用。控制台谷歌浏览器:注意:第 34 行 C:\wamp\www\britanicaBlueForm2\templatesHTML\php\adiantamento.php 中的数组到字符串转换.....我的第 34 行 => $a = json_decode($_POST['vetDespesas ']);回声 $a[0]; ....对不起,我是 php rs 的新手
  • 确实如此,因为$a[0]; 将返回vetDespesas 中的第一个对象,它是一个数组,因此您应该使用print_r($a[0]) 而不是echo
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多