通过在\Drupal\Core\Ajax\AjaxResponse::addCommand() 上使用对象\Drupal\Core\Ajax\InvokeCommand。
Ajax 可以与表单一起使用来提供各种东西。涉及的典型步骤:
- 创建一个表单。
- 在
::buildForm() 中使用#ajax 渲染元素。
- 创建回调。
有两种方式来响应 ajax 请求。您可以使用 AjaxResponse 对象或 HTML 进行响应,以替换可能是原始 HTML 或渲染数组的元素。
要调用您自己的 Javascript 函数(如您所愿),您必须使用 AjaxResponse 对象进行响应。
这是complete documentation of Ajax on Drupal 8。
这是示例:
部分::buildForm()带有Ajax渲染元素的实现:
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send'),
'#ajax' => [
'callback' => [$this, 'respondToAjax'],
]
];
这里是Ajax回调方法,形式相同:
/**
* @param array $form
* Form API array structure.
* @param array $form_state
* Form state information.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* Response object.
*/
public function respondToAjax(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new InvokeCommand('#example', 'ajaxSuccess'));
return $response;
}
您可以在这里找到list of all commands you can pass in the response。