wp_send_json

函数
wp_send_json ( $response, $status_code = null, $options = 0 )
参数
  • (mixed) $response Variable (usually an array or object) to encode as JSON, then print and die.
    Required:
  • (int) $status_code Optional. The HTTP status code to output. Default null.
    Required:
    Default: null
  • (int) $options Optional. Options to be passed to json_encode(). Default 0.
    Required:
定义位置
相关方法
wp_send_json_errorwp_send_json_successwp_shake_jswp_signonwp_site_icon
引入
3.5.0
弃用
-

wp_send_json: 这是一个WordPress的函数,用于向客户端发送JSON响应。它允许你将一个数组或对象编码为JSON,然后用适当的内容类型头将其发送给客户端。

向Ajax请求发送一个JSON响应。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function wp_send_json( $response, $status_code = null, $options = 0 ) {
if ( defined( 'REST_REQUEST' ) && 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, $options );
if ( wp_doing_ajax() ) {
wp_die(
'',
'',
array(
'response' => null,
)
);
} else {
die;
}
}
function wp_send_json( $response, $status_code = null, $options = 0 ) { if ( defined( 'REST_REQUEST' ) && 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, $options ); if ( wp_doing_ajax() ) { wp_die( '', '', array( 'response' => null, ) ); } else { die; } }
function wp_send_json( $response, $status_code = null, $options = 0 ) {
	if ( defined( 'REST_REQUEST' ) && 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, $options );

	if ( wp_doing_ajax() ) {
		wp_die(
			'',
			'',
			array(
				'response' => null,
			)
		);
	} else {
		die;
	}
}

常见问题

FAQs
查看更多 >