简体   繁体   English

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

[英]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.我有一个数组,我试图将它传递给正在传递的 php 文件,但它将该数组显示为字符串。 How do I convert the string to an array so I can go through it in php?如何将字符串转换为数组,以便我可以在 php 中遍历它? Here's my code:这是我的代码:

jQuery 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 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:我删除了JSON.stringify()并添加了var_dump() ,这是输出:

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您根本不需要JSON.stringify并检查所有内容是否成功通过使用

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

not the pring_r with concatenations不是带有串联的pring_r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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