2013-04-10 37 views
0

我在页面上有一个div,它将MySQL数据库中的数据(图片和文本)随机化并显示出来。基本上,每次刷新时都会显示不同的图片和文字。是否可以把一个按钮做同样的事情,而不必刷新整个页面?使用数据库中的数据刷新网页中的div

+0

是,这就是Ajax的用途。 – Whistletoe 2013-04-10 19:16:20

回答

1

使用jQuery $.ajax()$.html()

通过$.click()将jQuery $.ajax()连接到您的按钮。然后,对于返回的数据,请将div的内容设置为$.html()

发表一些代码,我会给出更多的细节。

0

对于您要做的事情,这可能有点复杂。但有了这个,你可以发送回一个以上的图像作为JSON和必须通过它们,你的成功函数循环等

jQuery的阿贾克斯后:

$("#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 

    } 
} 
相关问题