wp_send_json()
云策文档标注
概述
wp_send_json() 函数用于向 Ajax 请求发送 JSON 响应,自动设置 HTTP 头、编码数据并终止脚本执行。适用于 WordPress Ajax 处理,但在 REST API 请求中应使用 WP_REST_Response 或 WP_Error。
关键要点
- 核心功能:发送 JSON 响应到 Ajax 请求,自动调用 wp_die() 或 die() 终止执行。
- 参数说明:$response(必需,数组或对象)、$status_code(可选,HTTP 状态码)、$flags(可选,json_encode() 选项)。
- 注意事项:在 REST API 请求中使用时,会触发 _doing_it_wrong() 警告,建议改用 WP_REST_Response 或 WP_Error。
- 相关函数:依赖 wp_json_encode() 编码、wp_doing_ajax() 检测请求类型,与 wp_send_json_success() 和 wp_send_json_error() 相关。
代码示例
$return = array(
'message' => 'Saved',
'ID' => 1
);
wp_send_json($return);注意事项
- 使用 wp_send_json() 后无需再调用 wp_die() 或 exit(),函数会自动处理。
- 确保在 Ajax 回调中正确使用,避免在 REST API 场景下误用。
原文内容
Sends a JSON response back to an Ajax request.
Parameters
$responsemixedrequired-
Variable (usually an array or object) to encode as JSON, then print and die.
$status_codeintoptional-
The HTTP status code to output.
Default:
null $flagsintoptional-
Options to be passed to json_encode(). Default 0.
Source
function wp_send_json( $response, $status_code = null, $flags = 0 ) {
if ( wp_is_serving_rest_request() ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: WP_REST_Response, 2: WP_Error */
__( 'Return a %1$s or %2$s object from your callback when using the REST API.' ),
'WP_REST_Response',
'WP_Error'
),
'5.5.0'
);
}
if ( ! headers_sent() ) {
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
if ( null !== $status_code ) {
status_header( $status_code );
}
}
echo wp_json_encode( $response, $flags );
if ( wp_doing_ajax() ) {
wp_die(
'',
'',
array(
'response' => null,
)
);
} else {
die;
}
}
Skip to note 3 content
rmdundon
If this is a REST response (i.e. via the REST API), use WP_REST_Response or WP_Error, instead.
Skip to note 4 content
Aurovrata Venet
'Saved', 'ID' => 1 ); wp_send_json($return);NOTE: not need to include wp_die() or exit(0) after using wp_send_json() as it automatically calls wp_die() .