简体   繁体   中英

How to pass object (or array) to PHP from jQuery?

I have an array that I'm trying to pass to a php file which is passing, but it shows the array as a string. How do I convert the string to an array so I can go through it in php? Here's my code:

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;

CURRENT OUTPUT

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

** EDIT **

I removed JSON.stringify() and added var_dump() and this is the output:

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

}

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

如果你想用逗号重新加入数组,那么

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

You don't need JSON.stringify at all and you check that everything is passed successfully using

var_dump($department, $category, $attributes);

not the pring_r with concatenations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM