LoginSignup
23

More than 5 years have passed since last update.

javascriptでクロスドメインを越える

Last updated at Posted at 2016-05-25

Google皇帝に従ってSSL化しろよと思いますが
残念ながらなかなかそうはいかない場合もあって。

以前は

api.php
echo file_get_contents($_GET['url']);

こんな感じで経由してたけど
なんかできなくなった気がするのと
めんどくさいので
jsでできないかなーと思って探してたらありました。

jquery.fn/cross-domain-ajax at master · padolsey-archive/jquery.fn

https.html
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
<!-- <script type="text/javascript" src="https://raw.githubusercontent.com/padolsey-archive/jquery.fn/master/cross-domain-ajax/jquery.xdomainajax.js"></script> -->
<script type="text/javascript" src="https://rawgit.com/padolsey-archive/jquery.fn/master/cross-domain-ajax/jquery.xdomainajax.js"></script>

<script>
$(function() {
    $.ajax({
        type: 'GET',
        url: "http://6oolab.com/license.txt",
        dataType: 'html',
        success: function(data) {
            $.colorbox({html:data.responseText, width:"80%", height:"80%"});
        }, error:function(e) {
            console.log(e);
        }
    });
});
</script>

colorboxをつかう場面だったのでこうなりました。
スクレイピングするときも活躍しそう。

動作サンプル

(httpからhttp用) http://6oolab.com/xdomainajax
(httpsからhttp用) https://6oolab-com.ssl-netowl.jp/xdomainajax
ブラウザによって色々あるもよう。

追記
クロスドメインアクセスの最近 jquery.xdomainajax.js 読めないサイトあり?
htmlの構造によっては読めないものもあるみたい。

続・追記
raw.githubusercontent.comはtext/plainで読んでまうので
rawgit.comを使わせてもらう※注
CDN代わりにgithubを使いたい場合は外部サービスrawgithubを利用しよう

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
23