【问题标题】:Send array in ajax query在ajax查询中发送数组
【发布时间】:2013-05-09 20:35:55
【问题描述】:

我正在尝试使用 Jquery 的 $.post() 方法将数组从 JavaScript 发送到 PHP

我试过jQuery.serialize()jQuery.serializeArray()JSON.stringify(),都没有用。

这是我的代码:

$.post("ajax/"+action+"_xml.php",{'array': array},function(data){console.log(data);});

数组看起来像这样:

array["type"]
array["vars"]["name"]
array["vars"]["email"]

array["vars"] 有超过 2 个元素。

我的 php $_POST 变量中的结果是一个空数组(长度为 0)。

【问题讨论】:

    标签: php jquery ajax arrays post


    【解决方案1】:

    我建议您传递的数据采用以下结构:

    Javascript:

    var DTO = { 
        type: [1,2,3],
        vars: {  
            name: 'foo',
            email: 'foo@bar.com'
        }
    };
    
    var stringifiedData = JSON.stringify(DTO); 
    
    // will result in:
    //{"type":[1,2,3],"vars":{"name":"foo","email":"foo@bar.com"}} 
    
    $.post("ajax/"+action+"_xml.php",{'DTO': stringifiedData },function(data){
        console.log(data);
    });
    

    PHP:

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    
    $DTO = $_POST['DTO'];
    
    if(isset($DTO))
    {
        $assocResult = json_decode($DTO, true);
        var_dump($assocResult); //do stuff with $assocResult here
    }
    

    true 作为第二个参数传递给json_decode 将使其返回一个关联数组。

    http://php.net/manual/en/function.json-decode.php

    【讨论】:

    • 谢谢,我确实喜欢你。我构建了一个对象而不是数组,我使用了JSON.stringify,在我的 php 中我使用了json_decode。一切都运行良好,坦克很多。
    • +1 表示样品和两侧的细节。 . .如果它解释了为什么以前的方法不起作用,那将是完美的。 . .
    【解决方案2】:

    我不确定你是否可以发布这样的数组。

    拆分它应该可以正常工作:

    $.post("ajax/"+action+"_xml.php",{'type': array["type"], 'name' : array["vars"]["name"],...},function(data){console.log(data);});
    

    【讨论】:

    • 考虑到具有数十个键的数组,这种方式可能不是最好的。 (可能性)
    【解决方案3】:

    您需要将您的 javascript 数组转换为字符串,因为这是 post() 方法接受的所有内容。大多数人通过converting their array to JSON 执行此操作。

    【讨论】:

    • 既然你的回答没有问题,这里有一个反对意见;)
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2016-11-28
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多