如何从jQuery传递对象(或数组)到PHP?

时间:2012-11-18 21:35:34

标签: php javascript jquery

我有一个数组,我正在尝试传递给正在传递的php文件,但它将数组显示为字符串。如何将字符串转换为数组,以便我可以在php中完成它?这是我的代码:

的jQuery

$('#add-child').click(function()
{
    var _attributes = [];
    $('#attributes input').each(function()
    {
        _attributes.push($(this).val());
    });
    $.post('../assets/hub.php',{'task':'add-child','parent':$('#parent-id').val(),'value':$('#child-value').val(),'attributes':JSON.stringify(_attributes)},function(callback)
    {
        console.log(callback);
    });
});

PHP

case 'add-child':
    $department = $_POST['parent'];
    $category   = $_POST['value'];        
    $attributes = $_POST['attributes'];
    print($department.' : '.$category.' : '.$attributes);
break;

当前输出

test1 : test2 : ["sdfg","34","vsdf"] 

**编辑**

我删除了JSON.stringify()并添加了var_dump(),这是输出:

string(3) "114"
string(4) "asdf"
array(3) {
    [0]=>
    string(4) "asdf"
    [1]=>
    string(4) "ZVCX"
    [2]=>
    string(5) "asdfr"

}

2 个答案:

答案 0 :(得分:1)

$attributes = json_decode($_POST['attributes']);

如果你想用逗号再次加入数组,那么

$attributes = implode(',' , json_decode($_POST['attributes']));

答案 1 :(得分:1)

您根本不需要JSON.stringify,并使用

检查所有内容是否成功通过
var_dump($department, $category, $attributes);

不是带有连接的pring_r