Embed a View using AJAX

僤鯓⒐⒋嵵緔 提交于 2019-11-30 15:57:47

Ok, so I've found the answer.

Instead of loading the View from my own callback, I'm now loading the View from the regular ajax callback.

On my page, I create the view object, and add the configuration to Drupal.settings.

$view = views_get_view('taxonomy_term');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
  'views' => array(
    'ajax_path' => url('views/ajax'),
    'ajaxViews' => array(
      array(
        'view_name' => $view->name,
        'view_display_id' => $view->current_display,
        'view_args' => check_plain(implode('/', $view->args)),
        'view_path' => check_plain($_GET['q']),
        'view_base_path' => $view->get_path(),
        'view_dom_id' => 1,
        'pager_element' => $view->pager['element'],
      ),
    ),
  ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

Then I load my js, which adds the current filter from the location.hash to the settings. And finally, loads the View.

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) {
    var viewDiv = '.view-dom-id-' + data.view_dom_id;
    $('#content > div.limiter').html(response.display);
    // Call all callbacks.
    if (response.__callbacks) {
      $.each(response.__callbacks, function(i, callback) {
        eval(callback)(viewDiv, response);
      });
    }
  },
  error: function(xhr) {
    $('#content > div.limiter').html('<p id="artist-load-error">Error text.</p>');
    $('#block-request-0').hide();
  },
  dataType: 'json'
});

This way, the view loads through the regular flow, and everything works as expected =)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!