javascript 通过ajax到PHP的多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9945640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:19:00  来源:igfitidea点击:

Multidimensional Arrays via ajax to PHP

phpjavascriptarraysjquery

提问by Zac

Ok seriously struggling here. I am having some problems trying to send a multdimensional array to PHP via ajax. Here's what I have been trying:

好吧,在这里认真挣扎。我在尝试通过 ajax 将多维数组发送到 PHP 时遇到了一些问题。这是我一直在尝试的:

To simplify rather than copy paste a wall of code:

为了简化而不是复制粘贴代码墙:

    peoplearray[0]  =  [name] => 'john'
                       [age]  => '28'
                       [sex]  => 'Male'
    peoplearray[1]  =  [name] => 'julie'
                       [age]  => '20'
                       [sex]  => 'Female'

    main_array['item'] = 'x';
    main_array['something'] = 'x';
    main_array['another'] = 'x';

I want to get this to php via post. I figured I may aswell just join them together as I am multidimensional anyway thus :

我想通过post. 我想我也可以将它们连接在一起,因为无论如何我都是多维的:

    main_array['peoplearray'] = peoplearray;

now to do the ajax:

现在做ajax:

// var data = JSON.stringify(main_array);

var send = $.ajax({
        type: "POST",
        cache: false,
        url: "theurl",
        data: {data:main_array} //I do change this `main_array` when using the above stringify!
});


send.done(function(msg) {
console.log(msg);
})

in PHP I am just doing the following right now:

在 PHP 中,我现在正在执行以下操作:

$data= $_POST['data'];
print_r($data);

in firebug: (an empty string)

在萤火虫中: (an empty string)

when I have the var data = JSON.stringify(main_array);uncommented I get the following: [][

当我var data = JSON.stringify(main_array);取消注释时,我得到以下信息:[][

if i add $data = json_decode($_POST['data']);to the php I get:

如果我添加$data = json_decode($_POST['data']);到 php 我得到:

Array ( )

Basically the main_arrayI realise does not need to be an array and so I can get that stuff across no problem but what I need to do is get the peoplearrayover so that I can do some foreachetc... with it in php. Any help would be much appreciated I am sure I am just being stupid!

基本上,main_array我意识到不需要是一个数组,所以我可以毫无问题地解决这些问题,但我需要做的是peoplearray结束,以便我可以foreach在 php.ini 中做一些等...... 任何帮助将不胜感激我相信我只是愚蠢!

EDIT: The reasoning behind this is that peoplearraycould have 0 or 100 entries so I just need to get it to php so I can foreachit to do the DB inputs. If there is a better approach I would be very grateful to hear it as I am still pretty new to this.

编辑:这背后的原因是它peoplearray可能有 0 或 100 个条目,所以我只需要将它放到 php 中,这样我就可以foreach执行数据库输入。如果有更好的方法,我会很感激听到它,因为我对此还是很陌生。

EDIT: Thanks to Nicola's answer everything is passing fine except the important part which is mainarry.peoplearray - it is not appearing in the the return console.logand I cant access it in PHP. Any solutions on this or do I have to put the foreach intelligence in the javascript and just send everything individually?

编辑:感谢 Nicola 的回答,除了 mainarry.peoplearray 的重要部分之外,一切都很好——它没有出现在返回中console.log,我无法在 PHP 中访问它。对此有任何解决方案,还是我必须将 foreach 智能放在 javascript 中并单独发送所有内容?

采纳答案by Zac

I got it to work by keeping the peoplearrayseperate.

我通过保持peoplearray独立来让它工作。

So I did as Nicola said and created mainarrayas an object ie. declaring with curlies: {}

所以我按照 Nicola 说的做了,并创建mainarray了一个对象,即。用卷曲声明:{}

The peoplearrayI left as an array ie declaring with [], however then name,age&sexfields I created as an object ie. {} and then .push()them into the the peoplearray.

peoplearray余留作为阵列即具有声明[],但是然后name,age&sex字段我作为对象,即创建。{} 然后将.push()它们放入peoplearray.

Then the ajax looked as follows:

然后ajax看起来如下:

var send = $.ajax({
        type: "POST",
        dataType: "json",
        cache: false,
        url: "theurl",
        data: {data:main_array, people:peoplearray} 
});

then with the PHP everything is available in the $_POST, and if you

然后用 PHP 一切都在 $_POST 中可用,如果你

echo json_encode($people); //or whatever var name it is stored as in the php 

the objects ie name,age,sexproperties are shown in the

对象即name,age,sex属性显示在

send.done(function(msg) {
console.log(msg);
})

回答by Nicola Peluchetti

First of all main_arrayis not an array but an object because in javascript there are no associative arrays and for this reason

首先main_array不是数组而是对象,因为在 javascript 中没有关联数组,因此

main_array['peoplearray'] = peoplearray;

is equivalent to

相当于

main_array.peoplearray = peoplearray;

and you should declare main_array like this

你应该像这样声明 main_array

var main_array = {};

then try to change your function like this:

然后尝试像这样更改您的功能:

var send = $.ajax({
        type: "POST",
        dataType: "json",
        cache: false,
        url: "theurl",
        data: {data:main_array} 
});

and server side

和服务器端

header('Content-type: application/json');
$data= $_POST['data'];
echo json_encode($data);