Google analytics and loading a page using ajax GET

2019-05-30 00:53发布

问题:

I have a mobile site which completely runs using AJAX, and hash code, basically each page click is a link, such as

<a href='http://some-domain.com/my-page-122.php" hash-id='122'>linkage</a>

Meaning that the page itself exists and it has ON IT google analytics page, HOWEVER, on the ajax request, I only ask to load a certein <div> on said page using jQuery's load(), so my question is: because the page is called for in it's entirety with the google analytics code and everything, will it still record it as a page view even though only a portion is injected to the page?

The reason why I'm asking is because this site is getting around 500 uniques per day, and we want to change it to this new AJAXy form, so not recording analytics is a big no-no.

回答1:

If you use jQuery you can bind to the global AjaxComplete event to fire a Pageview everytime an Ajax call completes:

jQuery(document).ajaxComplete(function(e, xhr, settings){
  var d = document.location.pathname + document.location.search + document.location.hash;
  _gaq.push(['_trackPageview', d]);
});

If you update the Anchor every time you do an Ajax call this will fire the full path including the anchor part of the url.

Note that if you load content using .load that has the Google Analytics Tracking code in it, it will run that code and fire a second pageview. So you want to make sure you don;t include the GATC on the ajax content to avoid double pageviews.



回答2:

Analytics won't record it automatically. Assuming you're using the asynchronous code you can record as many pageviews as you want by writing to the gaq array using an explicitly set URL:

_gaq.push(['_setAccount', 'UA-12345-1']);
_gaq.push(['_trackPageview', '/home/landingPage']);

In this case you can build whatever URL you want where they have '/home/landingPage'. Note that if _gaq was already properly instantiated and _setAccount was already pushed then you only need to push the _trackPageview.

Also, the event can be in code returned by your AJAX, or it can be in the click event of your button or whatever is launching the AJAX request.

See http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html#_gat.GA_Tracker_._trackPageview