为什么这会返回0?

时间:2015-11-13 17:05:30

标签: javascript php ajax wordpress

我正在尝试制作自定义验证码生成器。简而言之,服务器通过AJAX返回图像的URL,并在会话存储中保持与图像的关联。

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
        });
    }
}

我的问题是它的警报

0

我无法弄清楚原因。因为我知道正在调用success函数,所以PHP必定存在问题。

2 个答案:

答案 0 :(得分:2)

为什么要在$capmap之外设置set_animal_captcha()?如果你真的必须将它保持在set_animal_captcha之外,那么将$capmap设置为函数内的全局。像这样:

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 :(得分:-2)

请通过以下方式判断您返回某些价值的声明:

 die();