PHP返回数组的值

时间:2014-03-26 14:20:04

标签: php jquery arrays

我想onsubmit,获取页面上所有div的定位并返回div的id和绝对定位值。

这是我在控制台中得到数组外观的结果: [对象{name =" app1",coord =" 10,10"},对象{name =" app2",coord =" 60,10& #34;}]

一,我是否正确填充数组?二,如何打印并通过结果返回一个字符串?

HTML页面:

var apps = $(".block"),
            positions = [];

            $.each(apps, function (index, app) {
                var positionInfo = $(app).position();
                var input = $(this).attr('id');
                var lines = input.split('_');
                var appname = lines[0];

                positions.push({value: appname + "," + positionInfo.top + "," + positionInfo.left});
                console.log(appname + ":" + positionInfo.top + ":" + positionInfo.left);
            });

            $.ajax({
                type:  'post',
                cache:  false ,
                url:  'result_savechange.php',
                data:  {result:positions},
                success: function(resp) {
                    $('#mainCanvas').html(''); // Clear #content div
                    $('#mainCanvas').append(resp);
                } 
            });

PHP页面:

<?php 
    $string = '';

    foreach($_POST["result"] as $position){
        $string .= $position['value'];
    }

    echo $string;
?>

1 个答案:

答案 0 :(得分:0)

这里没有理由使用JSON。这种情况太过分了。就这样做:

$.ajax({
    type:  'post',
    cache:  false ,
    url:  'result_savechange.php',
    data:  {result: positions},
    success: function(resp) {
        alert(resp);
    } 
});

然后在PHP中,$_POST["result"]将是一个数组。

foreach($_POST["result"] as $position){
    echo $position['name'];
    echo $position['coord'];
}