在AJAX回调中调用自定义JS函数?


8

是否可以在AJAX回调中调用自定义JS函数?

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

是的。或者至少应该有可能。有什么特别的问题吗?
Mołot

Answers:


5

您不能运行任意脚本,但是如果您可以将JS功能包装在jQuery插件中,则可以使用它ajax_command_invoke来获得相同的效果,例如

$selector = 'body';
$method = 'myJqueryPlugin';
$args = array('arg1', 'arg2');

$ajax_commands[] = ajax_command_invoke($selector, $method, $args);

当它出现在前端时,它将执行与

$('body').myJqueryPlugin('arg1', 'arg2');

10

是的。

代码示例:

$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);

JS代码:

(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);

3
这也是一个很好的例子
Rotari Radu 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.