Est-il possible d'invoquer une fonction JS personnalisée dans un rappel AJAX?
function MY_MODULE_ajax_callback() {
// Define a new array to hold our AJAX commands.
$ajax_commands = array();
// Create a new AJAX command that replaces the #page text with our own text.
$ajax_commands[] = [CUSTOM JS FUNCTION]
// Return our commandS
return array('#type' => 'ajax','#commands' => $commands);
}
Vous ne pouvez pas exécuter un script arbitraire, mais si vous pouvez envelopper votre fonctionnalité JS dans un plugin jQuery, vous pouvez utiliser ajax_command_invoke
pour obtenir le même effet, par exemple.
$selector = 'body';
$method = 'myJqueryPlugin';
$args = array('arg1', 'arg2');
$ajax_commands[] = ajax_command_invoke($selector, $method, $args);
Lorsque cela sort à l'avant, il exécute quelque chose d'équivalent à
$('body').myJqueryPlugin('arg1', 'arg2');
Oui, ça l'est.
Échantillon de code:
$commands = array();
$commands[] = array(
'command' => 'your_js_callback', // the name of your javascript callback
'value1' => 'My first value',
'value2' => 'My second value',
);
Code JS:
(function($, Drupal) {
Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
alert(response.value1);
alert(response.value2);
}
})(jQuery, Drupal);