【发布时间】:2020-02-09 13:30:38
【问题描述】:
使用 jquery 创建数组。使用 ajax ($.post) 将数组和附加数据发送到 php。在 php 中参见 [object Object]。并且无法从[object Object]获取数据。
尝试了以下代码:
var data_to_send = []; // actually here is is input fields .serializeArray()
var cars = ["Sa,coma,ab", "Vol,coma,vo", "B,coma,MW"];
data_to_send.push(
{name: 'draft', value: 'some_value'},
{name: 'cars_init', value: {name: 'cars', value: cars}}
);
$.post( filename.php, data_to_send, function(data_process_invoices) {
$('#show_result').html(data_process_invoices).css('color', 'black');
});
在php中用echo '<pre>', print_r($_POST, true), '</pre><br/>';得到这样的
Array
(
[draft] => some_value
[cars_init] => [object Object]
)
试图从[cars_init] 得到一些东西。
$array = get_object_vars( $_POST['cars_init'] );
结果是[object Object]。
试过$array = json_decode(($array), true); 和foreach( $_POST['cars_init'] as $val ) { echo '<pre>', print_r( $val, true), '</pre><br/>'; }。结果什么也没看到。并且还会得到 php 错误 get_object_vars() expects parameter 1 to be object, string given 和 Invalid argument supplied for foreach()。据我了解php [cars_init] 是字符串......所以问题似乎是,如何将其转换为数组。
而不是[object Object] 只想得到这样的数组
(
[0] => Sa,coma,ab
[1] => Vol,coma,vo
[2] => B,coma,MW
)
如果我将 jquery 更改为 $.post( filename.php, {data_to_send}, function(data_process_invoices) {,我会得到一些 php 数组(带有 $_POST)。但在这种情况下获得额外的维度,我需要使用foreach 来改变(浪费资源)。
【问题讨论】:
标签: php jquery arrays json ajax