开发者

var transfert between php and javascript

I like to get a dir listing in php

glob("*.jpg");

or

$dir    = '.'; //requested directory to read
$notthat = array('.', '..');  //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include

so i like to send that array to a java开发者_如何学Cscript like that (slides = $listedfiles)

function startSlideshow(slides) { .. do something..}

What is the best way to do that ?


json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:

var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}


you can always just do an echo of it to a javascript :

echo ' <script type="text/javascript"> 
var filelist = [];
';

foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}

echo "</script>";


PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:

<script type="text/javascript">
  var slides = [];
  <?php
  foreach ($listedfiles as $file)
  {
    echo "slides[] = '" . addslashes($file) . "';\n";
  }
  ?>

  // ... do js stuff
</script>

Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜