【问题标题】:Getting imagepng in ajax response在ajax响应中获取imagepng
【发布时间】:2014-03-23 04:47:50
【问题描述】:

我正在为验证码创建图像,但无法在 ajax 响应中获取该图像。需要帮助。我的代码:

ajax部分

$.ajax({
    type : "GET",
    url : "captcha.php",
    data : get_captcha_data,
    cache : false,
    success : function(r){
        $("#captcha").html('<img src="' + r + '" />');
    }


    });

php部分

session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165);
$fg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5,  $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
print imagepng($im);

imagedestroy($im);

这里似乎有什么问题?

【问题讨论】:

  • 尝试 因为你不发送 src/url,你发送图像数据本身这是不可能的,尽管你可以发送一个 base64 编码的字符串生成的图像。
  • 第二部分怎么做?如何发送base64?并收到它..

标签: php jquery ajax dynamic-image-generation


【解决方案1】:

正如上面评论中所写,您可以简单地使用 captcha.png 作为源来实现图像:

$("#captcha").html('<img src="captcha.png">');

不需要 AJAX 请求,但要满足您的请求:

您的 PHP 部分可能类似于:

// Enable output buffering
ob_start();
imagepng($png);
// Capture the output
$imagedata = ob_get_contents();
// Clear the output buffer
ob_end_clean();

echo base64_encode($imagedata);

AJAX 部分可能看起来像

success : function(r){
    $("#captcha").html('<img src="data:image/png;base64, '+ r +' ">');
}

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 2014-10-29
    • 2014-06-15
    • 2015-03-30
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多