如何使用jQuery显示数据库中的图像

时间:2019-02-13 07:11:40

标签: php jquery mysqli

我在使用jquery显示图像时遇到问题。从数据库中检索图像,我想使用jquery显示它。下面是我的代码

index.php

<?php 
require_once("db.php");

if(isset($_POST['input'])):

$id = $_POST['id'];

    $selectImage = mysqli_prepare($link,"SELECT product_image FROM products WHERE id = ? ");
    mysqli_stmt_bind_param($selectImage, "i",$id);
    mysqli_stmt_execute($selectImage);
    mysqli_stmt_bind_result($selectImage,$image);
    mysqli_stmt_fetch($selectImage);

    if($image):
      echo $image;

    else:
       echo "no image to display";
    endif;

endif;
?>

ajax.php

function imgViews(){
    $(".imageView").click(function(){
        var id = $(this).attr("id");

        $.ajax({
                url: 'class/display_image.php',
                type: 'POST',
                data: {input: 'input',
                       id:id
                   },
                success:function(data){
                 ****display image*****
                },
                dataType: "text"
        });
    });
}
imgViews();

displayHere.html

<div id="imageContainer>
    <img src="img/...."> 
</div>

4 个答案:

答案 0 :(得分:0)

尝试一下

success:function(data){
   $('#imageContainer').html('<img src="'+data+'"/>');
},

答案 1 :(得分:0)

index.php

<?php 
require_once("db.php");
if(isset($_POST['input'])):
$id = $_POST['id'];
$selectImage = mysqli_prepare($link,"SELECT product_image FROM products WHERE id = ? 
");
mysqli_stmt_bind_param($selectImage, "i",$id);
mysqli_stmt_execute($selectImage);
mysqli_stmt_bind_result($selectImage,$image);
mysqli_stmt_fetch($selectImage);

if($image):?>
<div id="img_id"><?php echo $image; ?></div> 
<?php  
else: ?>
<div id="img_id"></div>
<?php 
endif;
endif;
?>

ajax.php

function imgViews(){
    $(".imageView").click(function(){
        var id = $('img_id').text().trim();

        if(id != ""){
             $.ajax({
                    url: 'class/display_image.php',
                    type: 'POST',
                    data: {input: 'input',
                           id:id
                       },
                    success:function(data){
                     $('#imageContainer').html('<img src="'+data+'"/>');
                    },
                    dataType: "text"
            });
        }
    });
  }
  imgViews();

答案 2 :(得分:0)

我希望这会对您有所帮助

$(“#imageContainer img”)。attr(“ src”,data);

答案 3 :(得分:0)

尝试一下

$('#pic').html('"<img src="'+ picURL + data +'"/>');