Embed a View using AJAX

前端 未结 1 859
别那么骄傲
别那么骄傲 2021-01-03 08:54

I have a view with one argument, and a set of exposed filters. When the user filters the view, the form is submitted using Ajax, and the filters are appended to the url usin

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 09:09

    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('

    Error text.

    '); $('#block-request-0').hide(); }, dataType: 'json' });

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

    0 讨论(0)
提交回复
热议问题