WordPress函数:wp_send_json_error 发送ajax错误结果

江河/ 2023年10月30日/ WordPress/ 浏览 437

函数原型:


wp_send_json_error( mixed $data = null, int $status_code = null, int $options )


将JSON响应发送回Ajax请求,表示失败。


如果$data参数是WP_Error对象,则处理对象中的错误并将其输出为错误代码和相应消息的数组。所有其他类型的输出都不需要进一步处理。


响应对象将始终具有一个值为false的成功密钥。如果$data参数中的任何内容被传递给函数,它将被编码为数据键的值。


参数说明:


$data,将数据编码为JSON,然后打印并结束程序。


$status_code,HTTP CODE


函数源码:


function wp_send_json_error( $data = null, $status_code = null, $options = 0 ) {
	$response = array( 'success' => false );

	if ( isset( $data ) ) {
		if ( is_wp_error( $data ) ) {
			$result = array();
			foreach ( $data->errors as $code => $messages ) {
				foreach ( $messages as $message ) {
					$result[] = array(
						'code'    => $code,
						'message' => $message,
					);
				}
			}

			$response['data'] = $result;
		} else {
			$response['data'] = $data;
		}
	}

	wp_send_json( $response, $status_code, $options );
}


使用举例:


$error = new WP_Error( '001', 'No user information was retrieved.', 'Some information' );

wp_send_json_error( $error );


$nonce = $_POST['_wpnonce_name'];
if ( empty( $_POST ) || ! wp_verify_nonce( $nonce, 'my-nonce' ) ) {
	wp_send_json_error(); // sends json_encoded success=false
}


发表评论

暂无评论,抢个沙发...

客服 工单