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
檢視更多 >