确定到目前为止,我有以下代码可以在我的'照片'目录中显示随机照片:
<html>
<head>
<title>AWESOME Random Images</title>
<?php
function randomimages(){
$dirname = isset($_REQUEST['dir'])? $_REQUEST['dir'] : './photos/';
$numimages = isset($_REQUEST['num'])? $_REQUEST['num'] : 20;
$pattern = '#\.(jpg|jpeg|png|gif|bmp)$#i';
$files = array();
if($handle = opendir($dirname)){
while(($file = readdir($handle)) !== false){
if(preg_match($pattern, $file)){
array_push($files, "<center><img src='" . $dirname . $file . "' alt='' /></center>");
}
}
closedir($handle);
shuffle($files);
}
return implode("<center><br/>", array_slice($files, 0, $numimages)) . "<br/></center>";
}
?>
</head>
我在目录中有500多张照片,我正在寻找一种方法来添加一个按钮,该按钮将显示另外20张照片而无需重新加载页面。如果可能的话,我希望有人可以指出我正确的方向。
答案 0 :(得分:0)
您可以使用AJAX动态加载新内容。使用jQuery库非常简单:
$.ajax({
url: "http://example.com/images.php",
done: function( data ) {
if ( console && console.log ) {
console.log(data);
}
});
此代码将从http://example.com/images.php
url获取新数据并登录到控制台(您可以随意执行任何操作,例如生成html标记并插入DOM。
查看jQuery手册以获取更多示例http://api.jquery.com/jQuery.ajax
不要忘记准备这个新文件images.php
以返回数据,例如。 JSON
。你还需要传递一些变量,例如。比如要加载的图像类别,限制或页码。
答案 1 :(得分:0)
1-首先,您应该将您的操作代码放入<div>
。
2-然后,您应该使用ajax重新加载<div>
。为此,您应该编写一个javascript函数(在<script></script>
)
3-最后,在按钮onclick
(onclick="functionname()
“)中写下ajax函数的名称
.load()
方法可能会对您有所帮助:http://api.jquery.com/load/
答案 2 :(得分:0)
好的......所以我知道JQuery,这对我来说最简单。看看这个例子。它是独立的。实际上,您可以根据需要为HTML页面命名。另一个页面需要调用get_words.php
,以便ajax可以工作。每次运行ajax时,它都会转储到console.log()
,以便您可以看到正在发生的事情。
show_words.html - 此页面显示内容。它以html格式和json格式对get_words.php
进行ajax调用。
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>)
<style>
table.word_list {border: 1px solid #C0C0C0; border-collapse:collapse; width:400px}
table.word_list th, td {border: 1px solid #C0C0C0; margin:2px; padding-right:10px;
padding-left:4px;}
</style>
<button id="more_words_table" type="button">More Words! (table)</button>
<button id="more_words_json" type="button">More Words! (json)</button>
<div id="counter" style="display:inline-block"></div>
<table id="tbl_word_list" class='word_list'>
<tr>
<th style="width:30%">Word</th>
<th>Meaning</th>
</tr>
<tbody>
</tbody>
</table>
<script>
$(document).ready(function(){
var word_count = 0;
var more_words = true;
$("#more_words_json").on("click",function(){
if (more_words===false) return;
var request =
$.ajax({
type: "POST",
url: "get_words.php",
data: { "offset" : word_count, "limit" : 5, "return" : "json"},
dataType: "json"
});
request.done(function(data){
console.log(data);
if (data.length!==0) {
word_count+=5;
$.each(data, function(i,item){
$("#tbl_word_list").append("<tr><td>"+item.word+"</td>"+
"<td>"+item.meaning+"</td></tr>");
});
update_counter();
}
else { no_more_words(); }
});
});
$("#more_words_table").on("click",function(){
if (more_words===false) return;
var request =
$.ajax({
type: "POST",
url: "get_words.php",
data: { "offset" : word_count, "limit" : 5, "return" : "table"},
dataType: "html"
});
request.done(function(data){
console.log(data);
if (data.length!==0) {
word_count+=5;
$("#tbl_word_list").append(data);
update_counter();
}
else { no_more_words(); }
});
});
function update_counter() {
$("#counter").html(word_count+" words displayed");
}
function no_more_words() {
more_words = false;
$("#counter").html("No more words available!");
}
});
</script>
get_words.php - 此页面会显示一些$_POST
值,然后打印一些将由主页上的ajax调用检索的数据。
<?php
$word_list = array("Amorphous: indefinite, shapeless", "Beguile: deceive", "Caprice: impulse", "Cascade: steep waterfall", "Cashmere: fine, delicate wool",
"Chrysalis: protective covering", "Cinnamon: an aromatic spice; its soft brown color", "Coalesce: unite, or fuse",
"Crepuscular: dim, or twilit", "Crystalline: clear, or sparkling", "Desultory: half-hearted, meandering", "Diaphanous: gauzy",
"Dulcet: sweet", "Ebullient: enthusiastic", "Effervescent: bubbly", "Elision: omission", "Enchanted: charmed", "Encompass: surround",
"Enrapture: delighted", "Ephemeral: fleeting", "Epiphany: revelation", "Epitome: embodiment of the ideal",
"Ethereal: celestial, unworldly, immaterial", "Etiquette: proper conduct", "Evanescent: fleeting", "Evocative: suggestive",
"Exuberant: abundant, unrestrained, outsize", "Felicity: happiness, pleasantness", "Filament: thread, strand", "Halcyon: care-free",
"Idyllic: contentedly pleasing", "Incorporeal: without form", "Incandescent: glowing, radiant, brilliant, zealous",
"Ineffable: indescribable, unspeakable", "Inexorable: relentless", "Insouciance: nonchalance", "Iridescent: luster",
"Languid: slow, listless", "Lassitude: fatigue", "Lilt: cheerful or buoyant song or movement", "Lithe: flexible, graceful",
"Lullaby: soothing song", "Luminescence: dim chemical or organic light", "Mellifluous: smooth, sweet",
"Mist: cloudy moisture, or similar literal or virtual obstacle", "Murmur: soothing sound", "Myriad: great number",
"Nebulous: indistinct", "Opulent: ostentatious", "Penumbra: shade, shroud, fringe", "Plethora: abundance", "Quiescent: peaceful",
"Quintessential: most purely representative or typical", "Radiant: glowing", "Redolent: aromatic, evocative",
"Resonant: echoing, evocative", "Resplendent: shining", "Rhapsodic: intensely emotional", "Sapphire: rich, deep bluish purple",
"Scintilla: trace", "Serendipitous: chance", "Serene: peaceful", "Somnolent: drowsy, sleep inducing",
"Sonorous: loud, impressive, imposing", "Spherical: ball-like, globular", "Sublime: exalted, transcendent",
"Succulent: juicy, tasty, rich", "Suffuse: flushed, full", "Susurration: whispering", "Symphony: harmonious assemblage",
"Talisman: charm, magical device", "Tessellated: checkered in pattern", "Tranquility: peacefulness", "Vestige: trace",
"Zenith: highest point",);
$offset = (isset($_POST['offset'])) ? $_POST['offset'] : 0;
$limit = (isset($_POST['limit'])) ? $_POST['limit'] : 5;
$return = (isset($_POST['return'])) ? $_POST['return'] : 'table';
// no more words... return empty json or nothing depending on the return type
if ($offset>=count($word_list))
{
if ($return=="json") { print "[]"; }
exit();
}
$subset = array_slice($word_list,$offset,$limit);
if ($return == 'json')
{
$data = array();
foreach ($subset as $i => $item)
{
list($word, $meaning) = explode(':',$item);
$data[] = array('word' => $word, 'meaning' => $meaning);
}
print json_encode($data);
}
else if ($return == 'table')
{
foreach ($subset as $i => $item)
{
list($word, $meaning) = explode(':',$item);
print "<tr><td>{$word}</td><td>{$meaning}</td></tr>";
}
}
?>