简体   繁体   中英

Pass an array from a php page to javascript on another page

i'm trying to update an array called "vars" on a page from an array stored on a php page

i got one page sending an array

var jsonString = JSON.stringify(vars);
$.ajax({
    type: "POST",
    url: "woepanel.php",
    data: {data : jsonString}, 
    cache: false,

    success: function(){
        $('#sent').attr("bgcolor", "#00FF00");
        $('#notsent').attr("bgcolor", "#FFFFFF");
    }

php receiving it and writing to a file

<?php
$vars=json_decode($_POST['data']); 
?>
<?php echo $vars ?>
<?php
file_put_contents('vars.txt', print_r($vars, true));
?>

and that part all works

then i need php to pass it to another page so in php i have

<?php
$varjava = '["' . implode('", "', $vars) . '"]';
?>

then in javascript i have

<script type="text/javascript">
function test() {
   var vars = <?php echo $varjava ?>;
   alert (vars);
};
</script>

Just encode it once again in JSON directly:

function test() {
   var vars = <?php echo json_encode($vars) ?>;
   alert (vars);
};

JSON is valid JavaScript when assigned to a variable or passed to a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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