我正在尝试让ajax正常工作,因此当用户输入邮政编码并单击提交时,会出现一个警报,说明他们输入的邮政编码。
我对AJAX真的很陌生,所以如果下面的代码很糟糕,请原谅我!
单击“提交”时,会出现一个警报框,但会显示整个页面的源代码,而不是中的消息postcode_ajax2
.
有人能帮忙吗?
function ajax_postcode_form_init() {
wp_register_script(\'ajax-login-script\', get_bloginfo(\'stylesheet_directory\'). \'/ajax-postcode-script.js\', array(\'jquery\') );
wp_enqueue_script(\'ajax-login-script\');
wp_localize_script( \'ajax-login-script\', \'ajax_login_object\', array(
\'ajax_url\' => admin_url( \'admin-ajax.php\' ),
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( \'wp_ajax_nopriv_ajaxlogin\', \'postcode_ajax2\' );
}
add_action(\'init\', \'ajax_postcode_form_init\');
function postcode_ajax2() {
$postcode = false;
if(isset($_POST[\'postcode\'])){
$postcode = $_POST[\'postcode\'];
}
echo \'Received postcode was: \' . $postcode;
die();
}
var $ = jQuery.noConflict();
$(document).ready(function(){
$(\'#postcode_checker\').on(\'submit\', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var postcode = $(\'#postcode\').val();
console.log(postcode);
$.ajax({
type: "POST",
url: ajax_login_object.ajaxurl,
data: {
action: "postcode_ajax2",
postcode: postcode
},
success: function(data) {
alert(data);
},
error : function(error){
console.log(error)
}
});
});
});
// JavaScript Document
SO网友:Abhik
将AJAX处理程序函数挂钩移到init
回调并将脚本注册挂接到wp_enqueue_scripts
. 附加处理程序回调的钩子是wp_ajax_nopriv_postcode_ajax2
.
function ajax_postcode_form_init() {
wp_register_script(\'ajax-login-script\', get_bloginfo(\'stylesheet_directory\'). \'/ajax-postcode-script.js\', array(\'jquery\') );
wp_localize_script( \'ajax-login-script\', \'ajax_login_object\', array(
\'ajax_url\' => admin_url( \'admin-ajax.php\' ),
));
wp_enqueue_script(\'ajax-login-script\');
}
add_action(\'wp_enqueue_scripts\', \'ajax_postcode_form_init\');
function postcode_ajax2() {
$postcode = false;
if(isset($_POST[\'postcode\'])){
$postcode = $_POST[\'postcode\'];
}
echo \'Received postcode was: \' . $postcode;
die();
}
add_action( \'wp_ajax_nopriv_postcode_ajax2\', \'postcode_ajax2\' );