将JavaScript数组传递给PHP并对其进行操作

时间:2015-02-07 21:48:44

标签: javascript php arrays

ARRAYTEST.HTML

<html>
<head>
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>

<input type="button" id="btn" value="go to php" onclick="show()">
<br><br>

<script type="text/javascript">
var a = new Array(3,4,5);
function show(){
    $.ajax({        
        type: "POST",
        url: "arra.php",
        data: {test : a},
        success: function() {
        alert("success");        
        }
    });
}
</script>
</body>

ARRA.PHP

<?php 
    $arr = $_REQUEST['test'];

    echo $arr[0];
    echo $arr[1];
    echo $arr[2];
?>

我是php新手。 这是我的code.am尝试使用ajax在javascript中将数组值发布到php。我没有得到我错的地方。 提前谢谢:)

3 个答案:

答案 0 :(得分:0)

更改您的javascript方法,以便将json数据发送到服务器:

$.ajax({        
    type: "POST",
    url: "arra.php",
    data: {test : JSON.stringify(a)},
    success: function(data) {
        alert("success " + data); // now you will see the echo-ed array elements on the alert message
    }
});

比你的php文件你可以这样读:

$arr = json_decode($_POST['test'], true);

echo $arr[0];
echo $arr[1];
echo $arr[2];

答案 1 :(得分:0)

您在示例链接中缺少jQuery库,如:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

并重新定义onclick="show()"

答案 2 :(得分:0)

您应该在代码中包含Jquery脚本:

<script src="jquery.js"></script>

同时移动<script>标记内的<html>标记:

<html>
    <head>
        <script src="jquery.js"></script>
    </head>
    <body>

    <input type="button" id="btn" value="go to php" onclick="show()">
    <br><br>

    <script type="text/javascript">
    var a = new Array(3,4,5);
    function show(){
        $.ajax({        
            type: "POST",
            url: "arra.php",
            data: {test : a},
            success: function() {
            alert("success");        
            }
        });
    }
    </script>
    </body>
</html>