LoginSignup
70
75

More than 5 years have passed since last update.

ajaxでクロスドメイン通信を実現するphp

Last updated at Posted at 2014-08-10

概要

ajaxでのクロスドメイン通信をする簡単な方法です。
phpを使用して実現します。

ネットを探していると、なんだか複雑に実装しているサンプルが多かったので、簡単・汎用なものをつくりました。
テキスト形式で取得しているので、あとから、JSONなりXMLなりレスポンスのデータ形式にあわせてパースすれば良いかと。

コード

html は以下のとおり。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function(){
    $('#getbtn').click(function(){
        var url = encodeURIComponent($('#url').val());
        $('#restxt').val('通信中...');
        $.ajax({
            type: "GET",
            url: "ajax.php?url="+url,
            dataType: "text",
            success: function(res){
                $('#restxt').val(res);
            }
        });
    });
});
</script>
</head>
<body>
<p>取得先URL</p>
<input type="text" id="url"></input>
<button id="getbtn">GET</button>
<p>結果領域</p>
<textarea id="restxt" style="width:100%;height:300px;"></textarea>
</body>
</html>

以下、汎用phpファイル 下の改良版を推奨

ajax.php
<?php
if(isset($_GET["url"])) echo file_get_contents($_GET["url"]);

【更新】
以下、@suin さんからのご指摘を受けての改良版です。
http: あるいは、 https: から始まるパス以外はエラーとなるようにしました。

@sounisi5011 さんからのご指摘をうけてさらに改良しました。

ajax.php
<?php
if(isset($_GET["url"]) && preg_match("/^https?:/",$_GET["url"])){

    echo file_get_contents($_GET["url"]);
}else{
    echo "error";
}

設置サンプル

設置サンプルおきました。
試しに以下のURLコピペして試してみてください。

郵便番号
http://zip.cgis.biz/xml/zip.php?zn=1120014
ニコニコ動画
http://ext.nicovideo.jp/api/getthumbinfo/sm500873
天気
http://weather.livedoor.com/forecast/webservice/json/v1?city=200010
Googleジオコーディング
https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
70
75
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
70
75