0

我需要在 drupal 中将块内容附加到请求彻底 ajax 的视图结果中。我怎样才能做到这一点?

4

1 回答 1

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

于 2012-12-11T21:12:32.363 回答