Use AJAX to display php generated image

前端 未结 6 1983
攒了一身酷
攒了一身酷 2021-01-25 23:44

I have a php script that randomly generates an image. Something like this:



        
相关标签:
6条回答
  • 2021-01-25 23:56

    Instead of $('#image').html('<img src="' + data + '">'), try $('#image').attr('src', data);

    0 讨论(0)
  • 2021-01-26 00:01

    The src attribute of an image tag actually expects an URL not actual JPEG data.

    Try this:

     $(function(){
          $('#button').click(function(){
              $('#image').attr('src', 'models/plugins/image.php?rand=' + Math.floor(Math.random()*1000) );
          });
     });
    
    0 讨论(0)
  • 2021-01-26 00:03

    I added another answer because I think that none of the previous answers solved the problem. I think, the only thing the OP wanted was to update(!) the image when the button is clicked. So there is no need for an Ajax request, just reload the image. And you can enforce that by appending a random query string to the image's src attribute.

    $('#button').click(function() {
        var $image = $('#image');
        var plainSrc = $image.attr('src').split("?")[0];  // disregard previous query string
        $image.attr('src', plainSrc + "?" + (new Date().getTime()));
    });
    
    0 讨论(0)
  • 2021-01-26 00:03

    The resulting image has to be base64 encoded to be included like that.

    So you need to do the following:

    • Edit the image
    • Get resulting image in data string.
    • To get image string, you either store it to filesystem and read it through file_get_contents() (useful for cache) or use imagejpeg() without location, which places the image in output buffer. To get the value from output buffer use ob_start() and ob_get_contents().
    • Convert data string of the image to base64 (using base64_encode())
    • Return this string to browser
    • Set image "src" field to "data:image/png;base64,[BASE64]" where [BASE64] is the string returned from PHP.
    0 讨论(0)
  • 2021-01-26 00:10

    The image you are calling is being cached by browser, use a query string at the end of your image url to let the browser thing its a new image and it should not use cached version.

    Something like this:

    $(function(){
        $('#button').click(function(){
            $.ajax({
                url: 'models/plugins/image.php?t='+((new Date).getTime()),
                success: function(data){
                    $('#image').html('<img src="' + data + '">')
                }
            })
        })
    })
    
    0 讨论(0)
  • 2021-01-26 00:13

    To use the image inside the src attribute you need to provide a valid URI, for example a data-URI:

    <?php
    $image = imagecreatetruecolor(400,200);
    
    // process image
    
    // create image URI
    ob_start();
    imagejpeg($image);
    echo "data:image/jpeg;base64,", base64_encode(ob_get_clean());
    ?>
    

    I once compiled a more detailed answer for a similar question.

    0 讨论(0)
提交回复
热议问题