ajaxでボタンを押すごとに写真の表示を変える

buttonをclickするごとに、var iを++;して、表示を変えます。

<body>
    <button class="button">写真を表示</button><br>
    <img src="img/01.gif">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</body>
<script>
var img = ['img/01.gif','img/02.gif','img/03.gif','img/04.gif'];
var i = 1;
$(document).ready(function(){
    $(".button").click(function(){
        $("img").attr("src", img[i]);
        i++;
        if(i == (img.length)){
            i = 0;
        }
    });
});
</script>

ははーん、これは色々応用できそうですね。

ajax

<style>
.box{
    width:200px;
    height: 200px;
    background-color:#ddd;
}
</style>
<body>
    <div class="box"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</body>
<script>
$(document).ready(function(){
    $(".box").hover(function(){
        $(this).css({
            "background-color":"#ff9999",
        });
    }, function(){
        $(this).css({
            "background-color": "#dddddd",
        });
    });
});
</script>

$(document).ready(function()
HTML=DOMの読み込みが終わったらfunction()の中の処理(=なにかしらの処理)を実行

書き方を変えて試してみます。

<script>
$(document).ready(function(){
    $(".box").hover(function(){
        $(".box").html("hello");
    }, function(){
        $(".box").html("你好");
    });
});
</script>

おお、すこし馴染んできました。

クリックされた時

$(document).ready(function(){
    $(".box").click(function(){
        $(".box").html("クリックされました");
    });
});

buttonがクリックされたら、.boxの表示を変える

<body>
    <div class="box">こんにちは</div>
    <button class="button">表示</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</body>
<script>
$(document).ready(function(){
    $(".button").click(function(){
        $(".box").html("クリックされました");
    });
});
</script>

なるほど!

少し応用して、Math.floor(Math.random * 配列の数)として、配列の乱数をつくると、おみくじも簡単にできますね♪

<body>
    <div class="box"></div>
    <button class="button">おみくじを引く</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</body>
<script>
var kuji = ['大吉','中吉','小吉','吉','凶','大凶']
$(document).ready(function(){
    $(".button").click(function(){
        var rand = Math.floor(Math.random() * 6);
        $(".box").html(kuji[rand]);
    });
});
</script>

ga.jsからのデータ送信はAjax?

ga.jsの最後の方でW.XMLHttpRequest;と書かれており、

df=function(a,b,c,d){
		var e=W.XMLHttpRequest;
		if(!e)return!1;
		var f=new e;
		if(!("withCredentials"in f))return!1;

onreadystatechangeでhttps://stats.g.doubleclick.net/j/collect? となっているので、
Ajaxで非同期で送っているようですな。

f.setRequestHeader("Content-Type","text/plain");
	f.onreadystatechange=function(){
		if(4==f.readyState){if(d)try{var a=f.responseText;
			if(1>a.length||"1"!=a.charAt(0))Ra("xhr","ver",a),b();
			else if...

つまり、cookieなどを取得し、ga.jsで処理して、Ajaxでサーバー側に送っているということでしょうか。
すると、Ajaxからですね。

gaがデータを送信しているように見えるdoubleclick.netとは?

doubleclick.net 
アクセスすると、doubleclickbygoogle にリダイレクトされます。。よくわからないですね。トラッキングのデータがすべて入ってくるので、広告関係をやっているのでしょうか?サイトを見ると、adコンテンツばかりです。
googleの検索アルゴリズムと、double clickが無関係(な訳ないか)なのか、どう連携しているのかも気になるところですが、運営がgoogleになっている。。
https://www.doubleclickbygoogle.com/

再び、ga.jsですが、どうやってデータを送っているのか、よくわかりません。この変だと思うのですが。。。

return"https:"==J.location.protocol||M.G?"https://ssl.google-analytics.com":"http://www.google-analytics.com"},
														Ce=function(a){
															this.name="len";this.message=a+"-8192"},
															De=function(a){
																this.name="ff2post";
																this.message=a+"-2036"},Sa=function(a,b,c,d){b=b||Fa;if(d||2036>=a.length)gf(a,b,c);
																	else if(8192>=a.length){
																		if(0<=W.navigator.userAgent.indexOf("Firefox")&&![].reduce)throw new De(a.length);

cookieの読み込み

document.cookieでcookieを全て取得します。

console.log(GetCookie('key1'));
function GetCookie(name){
	var result = null;

	var cookieName = name + '=';
	var allcookies = document.cookie;

	var position = allcookies.indexOf(cookieName);
	if(position != -1){
		var startIndex = position + cookieName.length;
		var endIndex = allcookies.indexOf(';', startIndex);
		if(endIndex == -1){
			endIndex == allcookies.length;
		}

		result = decodeURIComponent(allcookies.substring(startIndex, endIndex));
	}
	return result;
}

indexOfは全文検索。allcookieの中で、key3=のポジションを取得
indexOf(‘hoge’, n) は、nの位置から、hogeを全文検索
つまり、indexOf(‘;’, 308)は、308以降の次の’;’を検索
allcookie.substring()で、valueを切り抜いています。

console.log(document.cookie);
console.log(document.cookie.indexOf('key3=')); //position
console.log(308); // start index 
console.log(document.cookie.indexOf(';', 308)); // end index 311
console.log(document.cookie.substring(308, 311));

cookieの書き込み

phpはsetcookie, jsはdocument.cookie

<?php
setcookie("key1", "value1")
?>
<script>
	document.cookie = 'key2=value2';
</script>

有効期限を設定

<script>
	var key = 'fsa';
	var expire = new Date();
	expire.setTime( expire.getTime() + 1000 * 3600 * 24 * 7);
	document.cookie = 'key=' + encodeURIComponent(key)+ '; path = /sample.php; expires = ' + expire.toUTCString();
</script>

アフィリエイトタグとコンバージョンタグの仕組みについて

例えば、VCで広告を作成すると、以下のようなタグは発行される
sidは個人のidで固定, pidは広告の種類によって異なるので、おそらく広告ごとのid?
リンク先がurlでパラメーターとして送られているので、getで取得してsid, pidを保存、setCookieして、設定されたURLリダイレクトさせて、コンバージョンページに行ったら、jsで処理しているのか??

<script language="javascript" src="//ad.jp.ap.valuecommerce.com/servlet/jsbanner?sid=xxxxxxx&pid=yyyyyyyyy"></script><noscript><a href="//ck.jp.ap.valuecommerce.com/servlet/referral?sid=xxxxxxx&pid=yyyyyyyyy" target="_blank" rel="nofollow"><img src="//ad.jp.ap.valuecommerce.com/servlet/gifbanner??sid=xxxxxxx&pid=yyyyyyyyy" border="0"></a></noscript>

gaタグの挙動を理解する

最初gaタグは以下のような記述になっているかと思います。

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-xxxxx-x']);
    _gaq.push(['_trackPageview']);
    (function() {

        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();
</script>

ga.jsのダミーとして同じディレクトリにtest.jsを作ります。
test.js

console.log(obj[0]);

test.php
objの配列にidを入れて、test.phpからtest.jsを呼び込みます。

<script type="text/javascript">
    var obj = obj || [];
    obj.push('id:1');
    (function() {
        var sa = document.createElement('script');
        sa.type = 'text/javascript';
        sa.async = true;
        sa.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://') + '192.168.33.10:8000/test.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(sa, s);
    })();
</script>

配列のid:1がtest.jsに渡されて、console.logが実行されます。

test.jsの中身を以下に書き換えると

console.log(obj[0]);
console.log(location.pathname);

test.phpのlocation.pathnameが表示されます。

つまり、setAccountとtrackPageviewを配列としてga.jsに渡して、対象ページのユーザー情報、挙動やcookieをga.jsでcollectしているということですね。
  _gaq.push([‘_setAccount’, ‘UA-xxxxxx-x’]);
_gaq.push([‘_trackPageview’]);

あれ、もしかして、アフィリエイトのコンバージョンタグも同じ仕組み?? マジ?

Google Analyticsでip情報を取得する方法

Google Analytics -> 管理 -> プロパティ -> カスタム定義 -> カスタムディメンション をクリック
「+新しいカスタムディメンション」を押下

カスタム ディメンションを追加 で名前を追加
JavaScript(ユニバーサルアナリティクスのプロパティのみで有効)から、
ga(‘set’, ‘dimension1’, dimensionValue); をコピー

GA JSにdimension1 とphpのREMOTE_ADDRの情報を送る

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UAxxxxxx-xx', 'auto');
  ga('set', 'dimension1', <?php echo $_SERVER&#91;‘REMOTE_ADDR’&#93;; ?>);
  ga('send', 'pageview');

</script>

あとは、セカンダリディメンション・カスタムディメンションで指定した名前を見れば、ipアドレスを閲覧できますね。

ga.jsでは、タグから送られてきたdimension1とipアドレスを配列に入れて、processingしてgaにレポーティングいるだけですな。
なるほど!ga.jsはまだ途上だが、仕組み自体は少しづつ分かってきた!

javascriptでユーザー情報を取得

<script type="text/javascript">
document.write("HOST : " + location.host + "<br>");
document.write("HOSTNAME : " + location.hostname + "<br>");
document.write("PORT : " + location.port + "<br>");
document.write("REQUEST : " + location.pathname + "<br>");
document.write("CODE : " + navigator.appCodeName + "<br>");
document.write("BROWSER : " + navigator.appName + "<br>");
document.write("VERSION : " + navigator.appVersion + "<br>");
document.write("LANG : " + navigator.language + "<br>");
document.write("PLATFORM : " + navigator.platform + "<br>");
document.write("USERAGENT : " + navigator.userAgent + "<br>");
document.write("REFERER : " + document.referrer + "<br>");
document.write("DOMAIN : " + document.domain + "<br>");
document.write("SCREEN.W : " + screen.width + "<br>");
document.write("SCREEN.H : " + screen.height + "<br>");
document.write("SCREEN.COL : " + screen.colorDepth + "Bit" + "<br>");
</script>

ipアドレスがありませんね。
ga.jsでipに関する記述を見てみると、
line10: Xa=Va(“anonymizeIp”)
くらいしかみつけられません。

Google analyticsのユーザー エクスプローラはipアドレスではなく、ユーザー固有の数字のようです。