无法让google analytics在我的页面上运行,该页面使用AJAX加载其页面

Roe*_*and 2 html javascript ajax jquery

所以经过一个巨大的头痛,我让我的网站通过ajax加载其页面.原因是客户希望它像旧的Flash网站一样流动..呃.

无论如何,一切都花花公子,但后来我添加了谷歌分析跟踪器,它不再加载!

那么我是怎么做ajax的:

$("li.home a").click (function() {       
    ajax_load("index.php",this);
    return false;
});
$("li.location a").click (function() {
    ajax_load("location.php",this);
    return false;
});

etc...

function ajax_load(page,element) {

    // deals with making an element active in left nav
    $('#mainnav').find('li.active').removeClass('active');
    $(element).parent().addClass('active');

    // empty the wrapper, then add new content with a fade effect
    $("#wrapper").empty();
    $("#wrapper").css({'display' : 'none'})
    $.ajax({
        type: "POST",
        url: page,
        success: function(msg){            
            $("#wrapper").append(msg);
            $("#wrapper").fadeIn();
        }
    });

    // set the page hash, so we can add these pages to favorites if wanted
    var strLen = page.length;
    page = page.slice(0,strLen-4);
    window.location.hash = page;
}
Run Code Online (Sandbox Code Playgroud)

所有单独的页面都是php文件..当它们被加载时,会在文件的开头检查它是否是ajax请求.如果是..它会跳过标题并导航到内容,然后跳过页脚.这允许它在禁用javascript时工作.

因此,为了让谷歌分析能够处理ajax页面加载,我认为我可以简单地将谷歌跟踪代码粘贴在加载的区域内,当它是ajax请求时......

那不行!目前,唯一一个包含google anayltics跟踪代码的页面是平面图页面,因此您可以看到正在发生的事情.任何指针将不胜感激!

继续使用谷歌跟踪代码:

    <script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11737385-5");
pageTracker._trackPageview();
} catch(err) {}</script>
Run Code Online (Sandbox Code Playgroud)

//更新//

我相信这应该做到,谢谢Pekka!

    $.ajax({
    type: "POST",
    url: page,
    success: function(msg){            
        $("#wrapper").append(msg);
        $("#wrapper").fadeIn();
        pageTracker._trackPageview(page);
    }
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 6

There is a function you can use, _trackPageview. See the Google Analytics manual:

How do I track AJAX applications?

With a typical HTML page, you can use the URL to differentiate between multiple pageviews. But in an AJAX application, a request to the server is made without changing the URL of the page, making it difficult to track.

但是,通过调用_trackPageview函数,您可以为任何AJAX事件分配页面文件名.通常,在返回数据并对页面进行了所有更新之后,这将作为onreadystatechange函数的一部分完成.