当前位置 : 主页 > 网页制作 > JQuery >

如何通过jQuery.ajax将JavaScript数组发送到PHP?

来源:互联网 收集:自由互联 发布时间:2021-06-15
参见英文答案 Convert js Array() to JSon object for use with JQuery .ajax5个 我正在尝试通过jQuery.ajax将JavaScript数组发送到PHP页面,但该数组仅使用空值发送. 如果我在Chrome上打开F12控制台并检查JS对象
参见英文答案 > Convert js Array() to JSon object for use with JQuery .ajax                                    5个
我正在尝试通过jQuery.ajax将JavaScript数组发送到PHP页面,但该数组仅使用空值发送.

如果我在Chrome上打开F12控制台并检查JS对象,它就在那里.全部填满了.但是当我使用ChromePhp工具记录PHP变量时,它只显示空白值(同样,如果我遍历php-array,回显它的值,我得到所有空白).

我在这里很困惑.

这是我的示例代码:

<?php 
include 'ChromePhp.php';
if (isset($_GET['newUsers'])) {
    $newUsers = $_GET['newUsers'];
    ChromePhp::log($newUsers);
} else { ?>

<html>
<body>

    <script src="js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        var newUsers = [];

        newUser = [];
        newUser['nome'] = 'alvaro';
        newUser['idade'] = '34';
        newUsers.push(newUser);

        newUser1 = [];
        newUser1['nome'] = 'bia';
        newUser1['idade'] = '7';
        newUsers.push(newUser1);

        newUser2 = [];
        newUser2['nome'] = 'alice';
        newUser2['idade'] = '2';
        newUsers.push(newUser2);

        $.ajax({
            url: "testcookie.php",
            type: "GET",
            data: {
                'newUsers[]': newUsers
            }
        });

    </script>
</body>
</html>
<?php } ?>

根据第一条评论更新.现在我得传递对象,但不知道如何读取它的属性.已经尝试了$user [‘nome’]没有结果.

<?php 
include 'ChromePhp.php';

if (isset($_POST['newUsers'])) {

    $newUsers = $_POST['newUsers'];

    foreach ($newUsers as $user) {
        # code...
        # HOW DO I READ THE nome AND idade VALUES HERE?
    }

} else { ?>

<html>
<body>

    <script src="js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        //var newUsersObj = {};
        var newUsers = [];

        newUser = {};
        newUser['nome'] = 'alvaro';
        newUser['idade'] = '34';
        newUsers.push(newUser);

        newUser1 = {};
        newUser1['nome'] = 'bia';
        newUser1['idade'] = '7';
        newUsers.push(newUser1);

        newUser2 = {};
        newUser2['nome'] = 'alice';
        newUser2['idade'] = '2';
        newUsers.push(newUser2);

        $.ajax({
            url: "testcookie.php",
            type: "POST",
            data: {
                'newUsers[]': newUsers
            },
            success: function () {

            },
            error: function () {

            }
        });

    </script>
</body>
</html>
<?php } ?>
只需传递数组或对象,jQuery就会自动将数组或对象转换为正确的参数,如a = [1,2] – >一个[] = 1&安培;一个[] = 2

data: {
    'newUsers': newUsers
 }

实现这一目标的内部功能是http://api.jquery.com/jQuery.param/

网友评论