简体   繁体   中英

Assigning php POST array to Javascript array

I know this may sound similar to some past Q/As, I think mine is slightly different though.. I have a webpage which I want to dynamically load text file information. I upload the text file through an iframe and I want to save this information from php to Javascript. Whenever I try to save this as a regular variable it doesn't work so I have tried to do this by saving this information as a part of the $_POST array under a hidden form named $_POST['hidden_form']. Whenever I try to read the php into Javascript, I keep getting an error "Unexpected token ILLEGAL." I have tried the following two codes:

for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
  echo "saved_form[$i]='" . $_POST['hidden_form'][$i]. "';\n";
}

and saved_form = <?php echo json_encode($_POST['hidden_form']); ?>; saved_form = <?php echo json_encode($_POST['hidden_form']); ?>;

Assigning a php array into a javascript array

I think the error has to do with the " ' " needed to specify the array but not sure. I have no idea where to go from here so any help would be GREATLY appreciated. If there are better methods to do this please let me know. Thanks in advance!

saved_form = '<?php echo addslashes(json_encode($_POST['hidden_form'])); ?>';

Or

for($i=0;$i< count($_POST['hidden_form']) ;$i++)
{
  echo "saved_form[$i]='" . addslashes($_POST['hidden_form'][$i]) . "';\n";
}

Both should work, probably had quotes breaking something?

the best way i have used is,

text/javascript

var saved_form = <?php echo json_encode($_POST['hidden_form']) ?>

Please note there are no Quotes around the php so your saved_form is an Object not a string json string witch would require you to to use var form_object = eval(saved_form)

@Lee might have meant this?

Just a note though i would not use the Raw $_POST pass it to a function that can loop though and addSlashes every value inside the post some thing like

<?php
function arr_addSlashes($array){
    $ret = array();
    foreach($array as $k => $v){
        $ret[$k] = addSlashes($v);
    }
    return $ret;
}
?>

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