我有一个数组,我试图将其传递给正在传递的 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"
}
最佳答案
您根本不需要 JSON.stringify
,您可以使用以下命令检查所有内容是否已成功传递
var_dump($department, $category, $attributes);
不是带有串联的pring_r
关于php - 如何从 jQuery 将对象(或数组)传递到 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13444857/