使用 Google Analytics 跟踪 AJAX 请求 [英] Using Google Analytics to track AJAX requests
问题描述
我正在更改网站的很大一部分以使用 jQuery Address 的深层链接 AJAX 功能.我正在使用 mysite.com/#!/page1/subpage/
等 URI.
I'm changing a big section of a website to use jQuery Address' deep linking AJAX features. I'm using URIs like mysite.com/#!/page1/subpage/
and so on.
我已经阅读了很多关于使用 _gaq.push()
函数跟踪流量的文章,但我想知道是否可以用更传统的方式来实现...
I've read a good bit about tracking traffic with the _gaq.push()
function, but I was wondering if it was possible to do it in a bit more traditional fashion...
每个 AJAX 请求调用一个 PHP 函数,该函数构建一个页面并在 <HTML>
包装器中返回它,这让我可以轻松定义自定义页面标题等.
Each AJAX request calls a PHP function that builds a page and returns it in an <HTML>
wrapper, which lets me easily define custom page titles and so on.
如果我将分析代码放在那个页面上,调用该页面的 jQuery 会触发它跟踪访问吗?
If I put the analytics code on that page, will jQuery calling that page trigger it to track the visit?
推荐答案
好吧,你可以使用 jQuery 的 AJAX Events 来全局监听 AJAX 请求,然后将索引推送到 _gaq
数组上(这看起来像最易于维护的方法):
Well you can use jQuery's AJAX Events to globally listen for AJAX requests and then push an index onto the _gaq
array (this seems like the most maintainable approach):
$(document).on('ajaxComplete', function (event, request, settings) {
_gaq.push(['_trackPageview', settings.url]);
});
请注意 .on()
是 jQuery 1.7 中的新内容,在这种情况下与 .bind()
相同.
Note that .on()
is new in jQuery 1.7 and is the same as .bind()
in this case.
另请注意,我还没有测试为全局 AJAX 事件传递的参数的内容.
Also note that I have not tested the contents of the arguments passed for global AJAX events.
更新
您还可以使用 $.globalEval()
来解析加载在 AJAX 响应正文中的脚本:http://api.jquery.com/jquery.globalEval/
You can also use $.globalEval()
to parse scripts loaded in an AJAX response body: http://api.jquery.com/jquery.globalEval/
success: function(data) {
var dom = $(data);
dom.filter('script').each(function(){
$.globalEval(this.text || this.textContent || this.innerHTML || '');
});
$('#mydiv').html(dom.find('#something').html());
}
来源:jQuery - HTML 中的脚本标签被 jQuery 解析出来,不执行
这篇关于使用 Google Analytics 跟踪 AJAX 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!