_ajax_wp_die_handler()
云策文档标注
概述
_ajax_wp_die_handler() 是处理 Ajax 请求时 wp_die() 的处理器,用于终止 WordPress 执行并显示错误消息的 Ajax 响应。
关键要点
- 函数用于处理 Ajax 请求中的错误,通过 wp_die() 调用。
- 参数包括必需的错误消息 $message、可选的错误标题 $title(未使用)和控制行为的 $args 数组。
- 默认设置响应状态码为 200,支持通过 _wp_die_process_input() 处理输入参数。
- 函数会设置 HTTP 状态头、防止缓存的头部,并根据参数决定是否终止执行。
代码示例
function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
// Set default 'response' to 200 for Ajax requests.
$args = wp_parse_args(
$args,
array( 'response' => 200 )
);
list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
if ( ! headers_sent() ) {
// This is intentional. For backward-compatibility, support passing null here.
if ( null !== $args['response'] ) {
status_header( $parsed_args['response'] );
}
nocache_headers();
}
if ( is_scalar( $message ) ) {
$message = (string) $message;
} else {
$message = '0';
}
if ( $parsed_args['exit'] ) {
die( $message );
}
echo $message;
}注意事项
- 错误标题 $title 参数在函数中未实际使用,但为保持一致性保留。
- 函数内部使用 _wp_die_process_input() 处理参数,确保与 wp_die() 其他处理器行为一致。
- 如果 $args['response'] 为 null,则不会设置状态头,以支持向后兼容性。
- 消息 $message 必须是标量类型,否则会被转换为字符串 '0'。
原文内容
Kills WordPress execution and displays Ajax response with an error message.
Description
This is the handler for wp_die() when processing Ajax requests.
Parameters
$messagestringrequired-
Error message.
$titlestringoptional-
Error title (unused). Default empty string.
$argsstring|arrayoptional-
Arguments to control behavior.
Default:
array()
Source
function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
// Set default 'response' to 200 for Ajax requests.
$args = wp_parse_args(
$args,
array( 'response' => 200 )
);
list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
if ( ! headers_sent() ) {
// This is intentional. For backward-compatibility, support passing null here.
if ( null !== $args['response'] ) {
status_header( $parsed_args['response'] );
}
nocache_headers();
}
if ( is_scalar( $message ) ) {
$message = (string) $message;
} else {
$message = '0';
}
if ( $parsed_args['exit'] ) {
die( $message );
}
echo $message;
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |