心跳API

心跳API(Heartbeat API)是WordPress内置的简单服务器轮询API,允许近乎实时的前端更新。

 

工作原理

当页面加载时,客户端心跳代码设置一个间隔(称为“tick”)以每15-120秒运行一次。当它运行时,heartbeat收集数据以通过jQuery事件发送,然后将其发送到服务器并等待响应。在服务器上,管理ajax处理程序接收传递的数据,准备响应,过滤响应,然后以JSON格式返回数据。客户端接收到该数据并触发最后一个jQuery事件,以指示数据已被接收。

自定义心跳事件的基本过程:

  1. 向要发送的数据添加附加字段(JSheartbeat-send事件)
  2. 检测PHP中的发送字段,并添加附加响应字段(heartbeat_received过滤器)
  3. 在JS中处理返回的数据(JSheartbeat-tick

(您可以选择仅使用其中一个或两个事件,具体取决于您需要的功能。)

 

使用API

使用心跳API需要两个独立的功能:用JavaScript发送和接收回调,以及用PHP处理传递数据的服务器端过滤器。

 

向服务器发送数据

当心跳向服务器发送数据时,可以包含自定义数据。这可以是要发送到服务器的任何数据,也可以是一个简单的true值,表示您需要数据。

jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
	// Add additional data to Heartbeat data.
	data.myplugin_customfield = 'some_data';
});

 

在服务器上接收和响应

在服务器端,您可以检测这些数据,并向响应中添加附加数据。

/**
 * Receive Heartbeat data and respond.
 *
 * Processes data received via a Heartbeat request, and returns additional data to pass back to the front end.
 *
 * @param array $response Heartbeat response data to pass back to front end.
 * @param array $data     Data received from the front end (unslashed).
 *
 * @return array
 */
function myplugin_receive_heartbeat( array $response, array $data ) {
	// If we didn't receive our data, don't send any back.
	if ( empty( $data['myplugin_customfield'] ) ) {
		return $response;
	}

	// Calculate our data and pass it back. For this example, we'll hash it.
	$received_data = $data['myplugin_customfield'];

	$response['myplugin_customfield_hashed'] = sha1( $received_data );
	return $response;
}
add_filter( 'heartbeat_received', 'myplugin_receive_heartbeat', 10, 2 );

 

处理响应

回到前端,您可以处理接收这些数据。

jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
	// Check for our data, and use it.
	if ( ! data.myplugin_customfield_hashed ) {
		return;
	}

	alert( 'The hash is ' + data.myplugin_customfield_hashed );
});

并非每个功能都需要这三个步骤。例如,如果您不需要向服务器发送任何数据,则可以只使用后两个步骤。