【发布时间】:2015-11-13 17:05:29
【问题描述】:
我正在尝试制作自定义验证码生成器。简而言之,服务器通过 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肯定有问题。
【问题讨论】:
-
您是否查看过浏览器的开发人员工具,了解 Ajax 请求实际返回的内容?
-
不要alerting,试试
console.log( animalUrl );可能更适合输出结果。 -
将
$capmap声明为函数内的全局变量——即:global $capmap;
标签: javascript php ajax wordpress