手动调用完全可以wp_die()
它可以很好地处理AJAX和非AJAX请求。只需确保返回有效的响应正文;e、 g.如果JS需要JSON响应,则返回JSON编码的字符串。
然而wp_send_json_error()
是的包装器wp_send_json()
其中使用wp_die()
, 所以你不需要打电话wp_die()
如果您正在使用wp_send_json_error()
或wp_send_json_success()
.
jQuery.ajax({
url: ajax_vars.ajax_url, // e.g. https://example.com/wp-admin/admin-ajax.php
data: { action: \'foo\', nonce: ajax_vars.foo_nonce },
dataType: \'json\', // <- we\'re expecting a JSON response
success ( res ) {
// Request succeeded, but we\'ve got an error from the server - e.g. Due to
// an expired nonce.
if ( ! res.success ) {
console.log( res.data );
// Request succeeded; no errors thrown on the server.
} else {
console.log( res );
}
},
// Request failed - e.g. Due to an internal server error (parse/syntax error,
// etc.).
error ( xhr, error, status ) {
console.log( error, status );
}
});
服务器端:此函数处理上述AJAX请求。
function ajax_foo_handler() {
if ( ! check_ajax_referer( \'foo\', \'nonce\', false ) ) {
wp_send_json_error( \'Invalid Request\' );
}
// Run your stuff...
wp_send_json_success( \'You may pass an array...\' );
}
add_action( \'wp_ajax_foo\', \'ajax_foo_handler\' ); // for authenticated users
add_action( \'wp_ajax_nopriv_foo\', \'ajax_foo_handler\' ); // for non-authenticated users