I\'ve defined a PHP callback function to handle the communication between server-side and client-side:
function json_render_modal_body() {
check_ajax_referer( THEME_PREFIX . \'-modals\', \'nonce\' );
$response = array( \'text\' => \'no\' );
$modal_id = null;
if ( isset( $_GET[\'modal_id\'] ) && ! $modal_id = filter_var( $_GET[\'modal_id\'], FILTER_SANITIZE_STRING ) ) {
wp_send_json_error( $response );
}
if ( ! $form = render_form( $modal_id ) ) {
wp_send_json_error( $response );
}
$response[\'text\'] = \'yes\';
wp_send_json_success( $response );
}
I\'ve told WordPress about this function, to handle the communication process:
add_action( \'wp_ajax_json_render_modal_body\', __NAMESPACE__ . \'\\json_render_modal_body\' );
add_action( \'wp_ajax_nopriv_json_render_modal_body\', __NAMESPACE__ . \'\\json_render_modal_body\' );
我已经注册/排队/本地化了JS脚本来处理AJAX请求。
This is what I\'ve localized:
wp_localize_script(
THEME_PREFIX . \'-modals\',
\'mbe_theme_modal\',
array(
\'ajax_url\' => admin_url( \'admin-ajax.php\' ),
\'nonce\' => wp_create_nonce( THEME_PREFIX . \'-modals\' )
)
);
This is what my JS script looks like:
var modal_id = jQuery( e.relatedTarget ).attr( "data-target" ).replace( "#", "" );
jQuery.get(
mbe_theme_modal.ajax_url,
{
action: "json_render_modal_body",
modal_id: modal_id,
nonce: mbe_theme_modal.nonce
},
function ( data ) {
console.log( data );
},
\'json\'
);
你知道我为什么一直
0
在我的AJAX响应中?
我还尝试从代码中删除nonce内容,并访问直接URL(domain.com/wp-admin/admin-ajax.php?action=json_render_modal_body&modal_id=some-modal-id
, 然而,我仍然继续得到0
.
我甚至尝试过用简单的文本响应来保持PHP函数的超级简单,但仍然得到了0
.