我试图通过ajax从PHP获取生成的映像。
Q.1当ajax呈现PHP时,它会显示一些符号,而不是单独运行PHP时所显示的图片。如何获得图像PHP输出而不是那些符号?
Q2。如何更改呈现到图像中的文本的字体大小?
PHP。
$im = imagecreate(300, 20);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 15, 1, '564545446', $black);
header ('Content-type: image/png');
imagepng($im, null, 3);
Ajax:
$.CaptchaLoad = function(){
$.ajax({
type:"POST",
complete: function(){
},
url:"../php/captcha.php"
}).done(function(feedback){
$('.CaptchaImg').html(feedback)
});
}
发布于 2013-12-28 23:04:46
答案1:
<img id="capcha" src="../php/captcha.php" height="30" width="300"/>
的.CaptchaImg
容器的标记。有用的链接:Refresh image with a new one at the same url。
回答2:
您可以使用其他参数来更改字体大小。例如,将GET
-parameter添加到图像加载脚本中。然后在服务器上捕获它,并在呈现capcha图像时做出反应。
客户端:
$.CaptchaLoad = function(){
var src = '../php/captcha.php',
stamp = (new Date()).getTime(),
font = 15, // or get it from somewhere else
url = src + '?stamp=' + stamp + '&font=' + font,
img = document.getElementById('capcha');
img.src = url;
img.className = 'capcha-loading';
img.onload = function(){ this.className = ''; };
img.onerror = function(){ this.className = 'capcha-error'; };
};
服务器端:
$font = isset($_GET['font']) ? abs((int)$_GET['font']) : 15;
// ^ ^
// asked font size default
// ... render image using obtained font size
P.S.:也忘了在PHP脚本的末尾使用imagedestroy($im);
。
发布于 2013-12-28 23:05:50
与其将“Content: image/png”发送到ajax,不如尝试发送HTML。更改您的captcha.php代码:
echo sprintf("<img src=\"%s\">", generate_img()); //return html to ajax
function generate_img() {
$im = imagecreate(300, 20);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagestring($im, $_POST["font_size"], 15, 1, $_POST["text"], $black);
imagepng($im, null, 3);
header('Content-type: image/png');
echo $im;
}
在ajax中:
$.ajax({
type:"POST",
data{
text : "My text",
font_size : 5
}
complete: function(){
},
url:"../php/captcha.php"
}).done(function(img){
$('.CaptchaImg').html(img); //.CaptchaImg can be a DIV element
});
https://stackoverflow.com/questions/20822861
复制