简体   繁体   English

PHP数组返回值

[英]PHP return value of an array

I would like to onsubmit, fetch the positioning of all the divs on the page and return the ids of the divs and the absolute positioning values. 我想onsubmit,获取页面上所有div的位置,并返回div的id和绝对定位值。

This is the result I get in the console of how the array looks: [Object { name="app1", coord="10,10"}, Object { name="app2", coord="60,10"}] 这是我在控制台中得到的数组外观的结果:[对象{name =“ app1”,coord =“ 10,10”},对象{name =“ app2”,coord =“ 60,10”}]

One, am I populating the array correctly? 一,我是否正确填充了阵列? Two, how can I print it and return a string via result? 二,如何打印结果并通过结果返回字符串?

HTML page: 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 page: PHP页面:

<?php 
    $string = '';

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

    echo $string;
?>

There's no reason to use JSON here. 这里没有理由使用JSON。 It's overkill for this scenario. 在这种情况下,这太过分了。 Just do this: 只要这样做:

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

Then in PHP, $_POST["result"] will be an array. 然后在PHP中, $_POST["result"]将是一个数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM