这里有什么交易?
JS函数的自定义。js\'
function validate() {
var email = jQuery("#billingemail").val();
if (isValidEmailAddress(email)) {
jQuery.ajax({
type: \'POST\',
url: ajaxurl,
data: {"action": "custome_ajax_email_check", "guestemail": email },
success: function(data){
data = jQuery.parseJSON(data);
if(data.result) {
alert(\'Email Exists\');
return false;
} else {
alert(\'Email Does Exists\');
return true;
}
}
});
} else {
return false;
}
}
点击“自定义”。js\'
$(\'#mwb_logincoupon\').on(\'click\', \'#validateguestemail\', function (e) {
e.preventDefault();
validateemail = validate();
PHP AJAX
add_action( \'wp_ajax_custome_ajax_email_check\', \'custome_ajax_email_check\' );
add_action(\'wp_ajax_nopriv_custome_ajax_email_check\', \'custome_ajax_email_check\');
function custome_ajax_email_check(){
$email = $_POST[\'guestemail\'];
// do check
if ( email_exists($email) ) {
$response->result = true;
}
else {
$response->result = false;
}
echo( json_encode( $response));
wp_die();
}
调试JS代码进入的脚本
success
功能,甚至触发
alert(\'Email Exists\')
.. 但是
return
函数中的语句从未检索到,因此
validateemail
始终返回
undefined
. 为什么?
SO网友:Brian Bruman
根据@SallyCJ建议使用await
我解释了这个新功能
async function doAjax(email) {
let result;
try {
result = await jQuery.ajax({
url: ajaxurl,
type: \'POST\',
data: {"action": "custome_ajax_email_check", "guestemail": email }
});
return result;
} catch (error) {
console.error(error);
}
}
然后我的
validate()
现在的功能很简单
function validate() {
var email = jQuery("#billingemail").val();
if (isValidEmailAddress(email)) {
doAjax(email).then( (data) => ajaxCallResult(data) )
}
. . . . .
然后最后
function ajaxCallResult(data){
data = jQuery.parseJSON(data);
. . . . . .
它正在工作。。非常有趣,了解
await
then
,
asynchronous
和
synchronous
电话等