2011-02-08 24 views
3

我有一个参数和一组暴露的过滤器。当用户过滤视图时,使用Ajax提交表单,并使用location.hash将过滤器附加到URL。使用AJAX嵌入视图

我的目标是在初始页面加载时过滤视图(如果过滤器存在于location.hash中)。

目前,我通过一个Ajax回调加载视图,这很好地工作。但是最大的问题是视图的Ajax不起作用。

这是加载视图的回调。

// Load the view object. 
$view = views_get_view('taxonomy_term'); 
$view->set_display('page'); 
$view->set_use_ajax(TRUE); 

// Pass the current tid as the argument. 
$view->set_arguments(array($tid)); 
// Set the current page. 
$view->set_current_page($page); 
// Set the exposed filters. 
$view->get_exposed_input(); 

// Execute. 
return $view->execute_display(); 

当我直接导航到该回调,一切正常。但不是当我通过Ajax加载它。

任何想法?

更新: 似乎Drupal.behaviors.ViewsAjaxView()由于某种原因不执行。如果我手动执行它,一切正常。

回答

8

好的,所以我找到了答案。

而不是从我自己的回调加载视图,我现在从常规的ajax回调加载视图。

在我的页面上,我创建了视图对象,并将配置添加到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'); 

然后我加载我的js,它将当前过滤器从location.hash添加到设置中。最后,加载视图。

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' 
}); 

这种方式,通过正常流动的观点负载,一切按预期工作=)

+0

真棒有这个这么少的信息在网络上(没有惊喜那里Drupal的)谢谢 – 2012-06-22 14:14:39