Heartbeat API

Heartbeat API是一种内置于WordPress的简单服务器轮询API,可实现近实时前端更新。

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

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

  • 向要发送的数据添加其他字段(JS心跳发送事件)
  • 检测PHP中发送的字段,并添加其他响应字段(heartbeat_received过滤器)
  • 处理返回的数据在JS(JS heartbeat-tick)

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

使用API

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

发送数据到服务器

当心跳发送数据到服务器时,您可以包括自定义数据。 这可以是要发送到服务器的任何数据,也可以是一个简单的真实值,表示您期望数据。

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

在服务器上接收和响应

在服务器端,您可以检测此数据,并向响应中添加其他数据。

// Add filter to receive hook, and specify we need 2 parameters.
add_filter( 'heartbeat_received', 'myplugin_receive_heartbeat', 10, 2 );
 
/**
 * 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).
 */
function myplugin_receive_heartbeat( $response, $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;
}

处理响应

返回到前端,然后可以处理接收到的数据。

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 );
});

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