2012-12-11 65 views
0

我需要在drupal中通过ajax请求查看结果的块内容。我怎样才能做到这一点?将静态数据附加到drupal-view

+0

在drupal7您可以使用上下文来实现这一目标。 – Lenin

+0

是的,在drupal7上,我一直在努力研究一些视图钩子,但没有成功。 – Topicus

回答

0

对于Drupal 7,你可以这样做,我相信。其中一些可能没有必要。它已经有一段时间,因为我设置的,但它为我的作品...

在你的template.php文件中添加此:

function _phptemplate_variables($hook, $vars) { 
    switch ($hook) { 
    case 'page': 
     // If the page was requested with the jQuery ajax functionalities, an HTTP header (X-Requested-With: XMLHttpRequest) 
     // will be sent to the server, making it possible to identify if we should serve the content as JSON 
     if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XmlHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']) { 
      // Now that we know that the page was requested via remote scripting (AJAX) we can serve the content as JSON 
      // by telling Drupal to use a different template for the page (in this case page-json.tpl.php) 
      $vars['template_files'] = is_array($vars['template_files']) ? $vars['template_files'] : array(); 
      $vars['template_files'][] = 'page-json'; 
     } 
     break; 
    } 
} 

在您的模板文件夹并将其命名为page-json.tpl.php创建一个模板文件:

<?php 
if($messages) { 
    $content = $messages.$content; 
} 
echo drupal_to_js($content); 
?> 

然后在您的script.js文件:

jQuery(document).ready(function($){ 
    if(typeof Drupal.settings.views != "undefined") 
    { 
     var data = {}; 
     // Add view settings to the data. 
     for (var key in Drupal.settings.views.ajaxViews[0]) { 
      data[key] = Drupal.settings.views.ajaxViews[0][key]; 
     } 
     // Get the params from the hash. 
     if (location.hash) { 
      var q = decodeURIComponent(location.hash.substr(1)); 
      var o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}; 
      $.each(q.match(/^\??(.*)$/)[1].split('&'), function(i,p) { 
      p = p.split('='); 
      p[1] = o.f(p[1]); 
      data[p[0]] = data[p[0]]?((data[p[0]] instanceof Array)?(data[p[0]].push(p[1]),data[p[0]]):[data[p[0]],p[1]]):p[1]; 
      }); 
     } 
     $.ajax({ 
      url: Drupal.settings.views.ajax_path, 
      type: 'GET', 
      data: data, 
      success: function(response) { 
      console.log(response); 
        // look into the log to see what results get back 
      }, 
      error: function(xhr) { 

      }, 
      dataType: 'json' 
     }); 
    } 
}); 

而且看到这个帖子一回合Drupal.settings.views: Embed a View using AJAX

这里就是我从信息来源: http://drupal.org/node/174008