dourun2990 2014-07-23 18:24 采纳率: 100%
浏览 77
已采纳

$ .post正在将对象数组更改为数组数组

I try to post via ajax some data. Watch sreenshot1. But jQuery automatic converts object to array. This can be seen in screenshot2 (chrome developer tools).

Data send to $.post:

enter image description here

Data inspect in chrome developer tools:

enter image description here

Edited:

Problems appear in PHP where I expect for Data property to be array of objects:

enter image description here

I want to read data like this:

foreach ($_POST["Data"] as $field)
{
    if ($field->Field == "username")
    {
            ...
    }
}
  • 写回答

2条回答 默认 最新

  • drasv0904 2014-07-23 20:47
    关注

    It's not really well spelled out in the PHP docs, but this is how it's supposed to work. For instance, the page on request variables has this to say about array-like cookies:

    If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

    <?php
      setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
      setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
    ?>
    

    That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

    In other words, when you send in:

    FormData[0][Field]: username
    FormData[0][Value]: test3
    

    PHP interprets this as an array of arrays, which looks like this:

    array(1) {
      [0]=> array(2) {
        ['Field'] => String(8) "username",
        ['Value'] => String(5) "test3"
      }
    }
    

    And you can parse it like so:

    foreach ($_POST["Data"] as $field)
    {
        if ($field['Field'] == "username")
        {
                ...
        }
    }
    

    Bear in mind that a PHP array is actually an ordered map. In other words, its perfectly suited for storing the key => value data you're passing in with your POST.

    You seem to be expecting $_POST to contain simple objects (aka stdClass) and it simply doesn't. Most SOAP helpers in PHP will give you simple object responses (which is a typical blending of behaviors from PHP). See this question for some ideas if you really want to translate every $_POST["Data"] field into an object. But that would be expensive and unnecessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?