[英]refresh div in web page with data from database
我在将MySQL数据库中的数据(图片和文本)随机化并显示它的页面上有一个div。 基本上,每次您单击刷新时,它都会显示不同的图片和文本。 是否可以放置一个按钮执行完全相同的操作,而不必刷新整个页面?
使用jQuery $.ajax()
和$.html()
。
通过$.click()
将jQuery $.ajax()
到您的按钮。 然后,对于返回的数据,使用$.html()
设置div
的内容。
发布一些代码,我将提供更多细节。
对于您要执行的操作,这可能有些复杂。 但是,使用此功能,您可以将多个图像作为JSON发送回去,并让您的成功功能在这些图像之间循环,等等。
jQuery ajax发布:
$("#yourbutton").click(function(e){ //when your button is clicked
e.preventDefault();
$.ajax({
type: 'POST', // or POST
url: 'ajax/testajax.php',
dataType: 'json',
data: {'getimage' : '1'}, // just post a 1 because you're getting a random image anyway
success: function(response) {
var obj = eval(response);
var image = obj[i];
var newPic = $('<img/>',{ //new img with the following attributes
src: image.src,
name: image.name,
width: '100' //and other attributes you want to include
});
newPic.appendTo("#container"); //apendd the new image to the container
}
});
});
的PHP:
if(!empty($_POST['getimage'])){
if($_POST['getimage'] == 1){
// do your query for the random image
$img = array(
array("name" => $row['imageName'], "src" => $row['imageSrc'])
);
echo json_encode($img); //send back as JSON
} else {
echo 'fail'; // send back a failure
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.