我知道这些无处不在,但我似乎在我的代码中看不到错误。我正在使用数据类型 json 进行简单的 ajax 调用。此调用似乎成功但不返回任何内容,并且警报打印undefined
。
javascript:
jQuery(document).ready(function() {
if(jQuery('#statesel').length) {
var dataString;
dataString = "nonce=" + dynoselect.post_dyno_select_nonce;
jQuery.ajax({
type: "POST",
url: dynoselect.ajaxurl,
dataType: "json",
data: dataString,
success: function(result) {
alert(result.status);
}
});
}
}
php:
<?php
add_action("init", "ci_enqueuer");
add_action("wp_ajax_dyno_select", "dyno_select");
add_action("wp_ajax_nopriv_dyno_select", "dyno_select");
function ci_enqueuer() {
wp_register_script('dyno_select_script', plugins_url('/js/dyno_select_script.js', __FILE__), array('jquery'));
wp_localize_script('dyno_select_script', 'dynoselect', array('ajaxurl' => admin_url('admin-ajax.php'), 'post_dyno_select_nonce' => wp_create_nonce('dyno_select_nonce')));
wp_enqueue_script('jquery');
wp_enqueue_script('dyno_select_script');
}
function dyno_select() {
$nonce = $_POST['nonce'];
//checking token, looking for funny business
if (!wp_verify_nonce( $nonce, 'dyno_select_nonce')) {
$result['status'] = 'nonce failed';
$result = json_encode($result);
echo $result;
die();
}
$result['status'] = 'success';
echo json_encode($result);
die();
}
?>
正如一个注释,这是使用 Wordpress 完成的,因此是init
函数。以为我会保留它以备不时之需。