我已经阅读了这个网站上的很多回复,但找不到我的代码存在的问题。
表格为:
<?php while (have_posts()) : the_post()?>
<form method=\'post\' id="dav-international" >
<label for="dav-address">Address:</label><input type="text" name="dav-address" id="dav-address"/>
<button type="submit" id="submit">Submit</button>
</form>
<?php endwhile;?>
功能位于
function.php
(主页已排队):
add_action(\'wp_enqueue_scripts\', \'dav_script\');
function dav_script(){
if (is_front_page()){
$dav_nonce = wp_create_nonce(\'contact_form\');
wp_localize_script(\'home-page\', \'ajaxObj\', array(
\'ajaxurl\' => admin_url(\'admin-ajax.php\'),
\'nonce\' => $dav_nonce,
));
}
}
add_action(\'wp_ajax_nopriv_dav_validation\', \'dav_form_validation\');
add_action(\'wp_ajax_dav_validation\', \'dav_form_validation\');
function dav_form_validation(){
global $wpdb;
if ($_SERVER["REQUEST_METHOD"] == \'POST\'){
check_ajax_referer(\'contact_form\');
$dav_address = sanitize_text_field($_POST[\'info\']);
$dav_ajax_data = array();
$dav_ajax_data[\'dav-address\'] = $dav_address;
echo json_encode($dav_ajax_data);
}
wp_die();
}
jQuery是:
var $j = jQuery;
$j(\'#submit\').click(function(e){
var $j = jQuery;
e.preventDefault();
if ($j(\'#dav-address\').val().length > 0){
var formInfo = $j(\'form\').serialize();
var formdata = {
action : \'dav_validation\',
_ajax_nonce: ajaxObj.nonce,
info : formInfo
}
$j.ajax({
type:\'post\',
url: ajaxObj.ajaxurl,
data: formdata,
success: function(data){
console.log(data);
}
})
}
});
我相信我正确地遵循了WordPress codex上的说明,但控制台继续输出0。我被困在这个问题上,似乎无法解决。