简体   繁体   中英

Refreshing a div that contains php include

I have a php code which displays a random file on pageload and on refresh. This code is in ../ads/food/responce.php which you will see in the other script below.

<?php
$ad = glob("../ads/food/*.php");
$adfood = $ad[mt_rand(0, count($ad) -1)];
include ($adfood);
?>

I am wanting to rotate the files displayed without having to refresh the page. ("like an image slider does")

What i have tried:

I have tried a script to refresh the div, but it seems to display a warning and not the file. You can see the error here http://whatanswered.com/food/what-can-i-do-with-cornflour.php

<script type="text/javascript">
$(document).ready(function() {
setInterval(function()
{
     $('#button').fadeOut("fast").load('../ads/food/responce.php').fadeIn("slow");
}, 10000);

});
</script>

<div id="button">
<?php include("../ads/food/responce.php");?>
</div>

It is just because the path ("../ads/food/*.php") doesnt lead to a folder that contains any php (ie : http://whatanswered.com/ads/ads/food ).

You have to write the path ../../ads/food/*.php this will lead to http://whatanswered.com/ads/food/ (which contains some php files)

I'm not sure if this will help, but here's some alternatives you can do:

  • Use iframes of sort to link to a page which will auto refresh and generate a new page
  • Use Ajax to embed the other page on your site.

Here's some reference for embedding a site with Ajax .

You have a couple of issues.

  1. Your responce.php file is already in the ads/food/ directory. As @edi9999 already mentioned your path should either be ../../ads/food/*.php or you could just use *.php .
  2. Your random file chooser will occasionally return responce.php. This likely won't cause any real problems, since response.php will simply be calling itself recursively. But if your file list is very short then there's a chance it could recurse quite a bit.
  3. You can have memory issues if your directory is very large (1000+ items).

You can exclude the responce.php file with this code. Also, there is an array_rand() function specifically for choosing a single item from an array.

$ad = glob("*.php");
$ad = array_filter($ad, function($name) {
    return preg_match('/response.php$/', $name) === 0 ;
}); 
include( $ad[array_rand($ad)] );

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