【发布时间】:2021-12-27 15:31:52
【问题描述】:
在我的 WordPress v5.8.2 中,我在 functions.php 中本地化了 ajax_url:
wp_enqueue_script('site_scripts', get_stylesheet_directory_uri() . '/assets/js/site-scripts.js', array('jquery'), null, true);
wp_localize_script('site_scripts', 'site_ajax', array('ajax_url' => admin_url('admin-ajax.php'), 'check_nonce' => wp_create_nonce('site_ajax_nonce')));
使用下面的 jQuery 脚本,我正在处理表单以检查 HTML 表单中的电子邮件 ID 是否已存在于 WordPress 中:
$(document).on("submit", "#form", function(e) {
e.preventDefault();
$email = $(this).find('input[name=email]').val(); // email
//ajax request, check if user exists
$.ajax({
type: "GET",
dataType: 'json',
url: site_ajax.ajax_url,
data: {
email: $email,
action: 'email_exists_check',
security: site_ajax.site_ajax_nonce
},
success: function(data) {
if (data.result) {
alert('Email exists!');
} else {
alert('Email does not exists!');
}
}
});
});
在单独文件中的 PHP 代码下方检查电子邮件:
add_action('wp_ajax_email_exists_check', 'email_exists_check');
add_action('wp_ajax_nopriv_email_exists_check', 'email_exists_check');
function email_exists_check() {
// Check nonce and email is set by ajax post.
if (isset($_POST['email']) && wp_verify_nonce('check_nonce', 'security')) {
// Sanitize your input.
$email = sanitize_text_field(wp_unslash($_POST['email']));
// do check.
if (email_exists($email)) {
$response = true;
} else {
$response = false;
}
// send json and exit.
wp_send_json($response);
}
}
如果电子邮件存在,上述整个代码无法发出警报。
我怎样才能使这段代码工作?
更新 #1
根据@Howard E 的建议,我发现包含email_exists_check() 函数的PHP 文件没有加载。
现在 PHP 文件已加载,我没有得到实际的 email_exists 状态。对于存在和不存在的电子邮件,警报始终为电子邮件不存在 (data.result == false)。
似乎email_exists_check 函数本身没有加载。我用下面的代码检查了日志,响应为 undefined 或 0:
success: function (json) {
console.log(json);
}
【问题讨论】: