问题描述:

Currently I am trying to return a PHP array in jQuery to use each element as a paremeter,

but actually I just get the last element of date.

I am quite new to jQ so modest knowledge and google skills won't help at all.

Here is my snippet as now.

 <script type="text/javascript">

var date = '<?php echo json_encode($date);?>';

var fam = '<?php echo json_encode($fam);?>';

$.each($.parseJSON(date),function(){

document.write(this);

});

</script>

Array for reference is

Array ( [0] => 22.06.2015 [1] => 23.06.2015 [2] => 24.06.2015 [3] => 25.06.2015 [4] => 26.06.2015 [5] => 29.06.2015 [6] => 30.06.2015 )

Thanks in advance,

JaHem

UPDATE

I don't think this is a problem of .each() anymore.

After I included the PHP-file in my jQuery-file

ob_start();

include("{$_SERVER['DOCUMENT_ROOT']}/awesome_path/application114/frames.php");

ob_end_clean();

The $date array goes from Array ( [0] => 22.06.2015 [1] => 23.06.2015 [2] => 24.06.2015 [3] => 25.06.2015 [4] => 26.06.2015 [5] => 29.06.2015 [6] => 30.06.2015 )
to
Array ( [0] => 30.06.2015 )

Can there be some trouble in the include ?

网友答案:

I couldn't quite reproduce your issue, but you could consider using JSON literals instead of strings; this way you don't need to parse it again.

<script type="text/javascript">

var dates = <?= json_encode($date) ?>;

$.each(dates, function() {
    document.write(this);
});

</script>
网友答案:
var dateArr = $.parseJSON(date);
$.each(dateArr, function(i, d) {
    console.log("Index: " + i);
    console.log("Date: " + d);
});

Edit: Please try to avoid document.write in the feature. Instead use console.log

网友答案:

I assumed the array as below and it works fine:

<?php
    $array = array( 0 => '22.06.2015', 1 => '23.06.2015', 2 => '24.06.2015', 3 => '25.06.2015', 4 => '26.06.2015', 5 => '29.06.2015', 6 => '30.06.2015' );

?>

Below is the jquery:

<script type="text/javascript">

    $(function(){

    var arr = '<?php echo json_encode($array); ?>';

    arr = $.parseJSON(arr);
    $.each(arr, function(key, value) {

        console.log(key+'====>'+value);

    });

});
    </script>
相关阅读:
Top