tohokuaikiのチラシの裏

技術的ネタとか。

今更ながらクロスドメインのAjaxをする場合

1分でわかるようにメモ。

Ajaxを送る側(http://send.example.com/send_ajax.html

<html>
<head>
<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>
  <script>
$(function(){
    $('#b').on('click', function(e){
        $.ajax({
          url: 'http://receive.example.com/catch.php',
          xhrFields: {
            withCredentials: true
          },          
          cache: false,
          data: {
              foo: 'var'
          }
        }).success(function(data, status, xhr){
            $('#foo').html(data);
        }).error(function(xhr, status, data){
            console.log("error"); 
        })
    });
});
  </script>
</head>
<body>
  <div id="foo">foo</div>
  <button id="b">click</button>
</body>
</html>

f:id:tohokuaiki:20181130154434p:plain

Ajaxを受信する側(https://receive.example.com/catch.php

<?php
session_start();
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Origin: http://send.example.com');
$_SESSION['counter'] += 1;
?>
Hello 
<?php
printf('<b>%d</b>times %s', $_SESSION['counter'], time());
?>

これで、先ほどボタンをクリックすると

f:id:tohokuaiki:20181130154702p:plain

となる。送り側の、xhrFields と受け側の header("Access-Control-Allow-Credentials: true"); はCOOKIEを使わないなら不要。