【问题标题】:Populate an html <img> with AJAX PHP request使用 AJAX PHP 请求填充 html <img>
【发布时间】:2017-06-03 18:06:13
【问题描述】:

大家好,我正在尝试使用 PHP 创建一个 captcha maker 的 OOP 样式

我有这个 Captcha 类来处理验证码图像的实际制作

class Captcha{

    private $image;
    private $background;
    private $linecolor;
    private $textcolor;

    private $text;
    private $possible;
    private $possibleLen;
    private $randText;

    public function getCaptcha(){
        $image = $this->image;
        $linecolor = $this->linecolor;
        $textcolor = $this->textcolor;

        $text = $this->text;
        $possible= $this->possible;
        $possibleLen = $this->possibleLen;
        $randText = $this->randText;

        // set the image size
        $image = @imagecreatetruecolor(150, 50) or die("Cannot Initialize new GD image stream");
        // set colors to the image
        $background = imagecolorallocate($image, 255, 250, 250); // color white
        imagefill($image, 0, 0, $background);

        $linecolor = imagecolorallocate($image, 112, 138, 144); //color gray
        $textcolor = imagecolorallocate($image, 49, 79, 79); //color greenish

        //draw random lines on canvas
        for($i=0; $i < 6; $i++) {
            imagesetthickness($image, rand(1,3));
            imageline($image, 0, rand(0,30), 120, rand(0,30), $linecolor);
        }

        session_start();

        // generate random text
        $text = "";
        $possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $possibleLen = strlen($possible);

        for($i=0; $i < 5; $i++ ){
            $randText = $possible[rand(0, $possibleLen - 1)];
            $text .= $randText;
            imagechar($image, rand(3, 5), $i, rand(2, 14), $randText, $textcolor);
        }

        // record digits in session variable
        $_SESSION['captcha'] = $text;

        return json_encode(array('image'=>$image));
    }
}

我有这个handler.php 文件,它会调用Captcha 类的方法:

require_once 'captcha.php';

if(empty($_POST['genCaptcha'])){
    return;
}

if(isset( $_POST['genCaptcha'] )) {
    $captcha = new Captcha();
    $result = $captcha->getCaptcha();
}

echo $result;

最后这是我的 html 和 jquery 代码,它将向 handler.php 文件发送 ajax 请求

<?php

    require_once 'captcha.php';
    require_once 'handler.php';

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.2.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.2.min.js"></script>
</head>
<body>
    <p><img id="captchaImg" src="" width="120" height="30" border="1" alt="CAPTCHA"></p>
    <button id="genCaptcha" type="button">Generate Captcha</button>
</body>

<script type="text/javascript">
    $(function() {
        $('#genCaptcha').on('click', function() {
            $.ajax({
                method: "POST",
                url:"handler.php",
                data: {genCaptcha:'1'},
                success: function(data){
                    var base64Image = data.image;
                    $('#captchaImg').attr('src','data:image...'+base64Image);
                },
                error: function (req, status, err) {
                    console.log('Something went wrong', status, err);
                }
            });
        });

    });
</script>
</html>

但我只是在我的 ajax 成功回调中得到 undefined 结果

感谢任何可以帮助我的人!

【问题讨论】:

  • getCaptcha() 你应该只return json,因为你稍后会在handler.php 中回显它
  • 您正在使用 AJAX 调用 handler.php 但您也在 HTML 页面上使用 require_once 调用它
  • dataType 应该是json,或者完全不使用它。 jQuery 会自己发现。
  • @Jeff 我尝试使用 getCaptcha() 方法返回 json 并在我的 ajax 请求中删除了 dataType 但它仍然不起作用。我尝试在 ajax 的success 回调中放置一个警报,每次我尝试生成验证码时它都会运行。但不幸的是,验证码的 根本没有更新
  • 我认为 AJAX 正在返回一个字符串。您必须使用 JSON.parse(data) 解析它

标签: php jquery html ajax


【解决方案1】:

由于您将参数传递给 __constructor(),因此您必须在创建新的 class 时传递这些参数。只需从构造函数中删除参数,它应该可以工作。

//if you have this
__construct($image, $background, $linecolor, $textcolor)
//class should be called like this
$captcha = new Captcha($image,$background,$linecolor,$textcolor);

//change it to this
__construct()
//since you call it like this
$captcha = new Captcha();

【讨论】:

  • 天哪,我忘记了。现在我从构造函数中删除了参数,现在它说我的类中的$image 变量是未定义的。Notice: Undefined variable: image
  • @ZyxSun 在你的课堂上,每当你提到 $image 时,它​​实际上应该是 $this-&gt;image
  • 是的,我在课堂上使用 `$this->image`,但我不知道为什么它仍然未定义
  • @ZyxSun 在getCaptcha() 你引用$image 但它应该是$this-&gt;image。当你提到private $image时,你必须像$this-&gt;image一样使用它
  • 我需要初始化我将在方法中使用的每个属性,还是有办法在一个部分中初始化它们?我不想在类的每个方法中重复使用$image = $this-&gt;image;
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 2013-07-25
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
相关资源
最近更新 更多