我正在尝试制作自定义验证码生成器。简而言之,服务器通过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必定存在问题。
答案 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();