在Drupal的自定义模块中,可以使用Drupal提供的Ajax API来实现异步交互。具体如下:
function mymodule_menu() { $items['mymodule/ajax'] = array( 'title' => 'Ajax Demo', 'page callback' => 'mymodule_ajax_callback', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); return $items; }
function mymodule_ajax_callback($ajax = NULL) { //如果有Ajax请求的话,返回异步内容 if($ajax) { $commands = array(); $commands[] = ajax_command_html('#ajax-div', 'This content is updated by Ajax'); return array('#type' => 'ajax', '#commands' => $commands); } //如果没有Ajax请求的话,返回页面内容 else { $output = 'This is content.'; $output .= '
(function($){ $(document).ready(function(){ $('#ajax-div').click(function(){ $.ajax({ url: Drupal.settings.basePath + 'mymodule/ajax', type: 'GET', dataType: 'json', data: { ajax: true }, success: function(data, textStatus, jqXHR) { Drupal.ajax['mymodule_ajax'].success(data, textStatus); }, error: function(jqXHR, textStatus, errorThrown) { alert('An Ajax error occurred.'); } }); }); }); })(jQuery);
Drupal.ajax['mymodule_ajax'] = new Drupal.ajax('mymodule_ajax', $('#ajax-div'), { url: Drupal.settings.basePath + 'mymodule/ajax', event: 'click', submit: { ajax: true }, progress: { type: 'throbber' }, });
通过上述步骤,即可在Drupal的自定义模块中成功地应用Ajax技术,实现异步交互。