简体   繁体   中英

How to preserv php string to javascript

I am trying to copy a string in a php array to localStorage and the string is a date in this format: 2016-06-15 But the string becomes calculated before stored. How do I preserv it as a string? Example:

<?php
  $test = array('2015-10-05','20151005');
  echo $test[0]."<br>";
  echo $test[1];
  echo '<script>localStorage["test1a"] = '.$test[0].';</script>';
  echo '<script>localStorage["test2a"] = '.$test[1].';</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>

This will output:

2015-10-05
20151005

And in localStorage:

test1a 2000
test1b 2015-10-05
test2a 20151005
test2b 20151005
<?php
  $test = array('2015-10-05','20151005');
  echo $test[0]."<br>";
  echo $test[1];
  echo '<script>localStorage["test1a"] = "'.$test[0].'";</script>';
  echo '<script>localStorage["test2a"] = "'.$test[1].'";</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>

Note the Additional Quotes added '"' wrapping the array variable. To explain why it does not store the value but calculate it is because you are throwing a string at browser and it interpretes as HTML or Javascript in this case.

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