dprnr5559 2015-11-13 17:05
浏览 63
已采纳

为什么这会返回0?

I'm trying to make a custom captcha generator. In short, the server returns a URL of an image through AJAX and keeps in session storage an association with the image.

PHP:

add_action( 'wp_ajax_set_animal_captcha', 'set_animal_captcha' );
$capdir = get_template_directory_uri() . '/assets/captcha/';
$capmap = array ( 'cat'  => $capdir . 'Captcha_Cat.png',
                  'dog'  => $capdir . 'Captcha_Dog.png',
                  'fish' => $capdir . 'Captcha_Fish.png' );
function set_animal_captcha ( )
{
    // returns image url of random animal and stores in session storage
    // a reference to that animal
    $randAnimal = array_rand($capmap,1);
    $_SESSION['randAnimal'] = $randAnimal;
    die(json_encode($capmap[$randAnimal]));
}

JS:

function capHandler ( imgid )
{
    // imgid: id of the image 

    this.imgid = imgid;
    this.formData = new FormData();
    this.formData.append('action', 'set_animal_captcha');
    this.set = function ( )
    {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            async: false,
            success: function ( animalUrl ) { alert(animalUrl); },
            error: function ( ) { alert("Error in getting captcha image") },
            cache: false,
            contentType: false,
            processData: false
        });
    }
}

My problem is that it's alerting

0

and I can't figure out why. Because I know the success function is being called, there must be something wrong with the PHP.

  • 写回答

2条回答 默认 最新

  • dosin84644 2015-11-13 17:33
    关注

    Why are you setting $capmap outside of set_animal_captcha()? If you really must keep it outside set_animal_captcha, then set $capmap as a global inside your function. Like this:

    function set_animal_captcha ( )
    {
        global $capmap;
        // returns image url of random animal and stores in session storage
        // a reference to that animal
        $randAnimal = array_rand($capmap,1);
        $_SESSION['randAnimal'] = $randAnimal;
        die(json_encode($capmap[$randAnimal]));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作