jQueryで別ドメインのページを読み込む

jQueryを使ってみて、あまりの簡便さに驚嘆している今日この頃。

今まで手を触れずにいたけれども、これは prototype.js も使ってみねば!

さて、jQuery では Ajax を簡単に扱えるわけですが、
原則的に Ajax は同一ドメイン内のファイルにしかアクセスできません。

そこで、別ドメインのページを読み込むためには PHP や Perl などで自ドメインのページとして読み込んだ後に、Ajax で表示するという手続きをとる必要があります。

そのための簡単な手続きを PHP + jQuery.js で実装してみましたので、アップしておきます。
(すでに誰かがアップしているような気もしますが・・・)

prototype.js でも基本的には使えるはずです。


※コメントしてくださっている方もありますが
Wordpressの仕様なのか、
クオーテーションマーク(”)が全角で表示されてしまうようです。
コピペで動作しないときは全角の(”)を半角の( ” )に置換して実行してみてください。

anotherDomain.html


<html><head>

<script type=”text/javascript” src=”jquery.js”></script>
<script type=”text/javascript”>
<!–
// Ajax の戻り値にこのエラーメッセージが含まれている場合には、
// ファイルの取得に失敗したと判断します。
ERROR_COMMENT “ReadingFileErrorOccurred”;

// submit 時の動作を指定
$(function(){
  $(
“#search”).submit(function(){
    
loadAnotherDomain($(“#url”).val());
    return 
false;
  });
});

// Ajax を使って、getpage.php に読み込みたいページのURLを渡します。
function loadAnotherDomain(url) {
  $(
“#result”).text(“Loading…”);

  $.ajax({
    
type“get”,
    
data: {
    
“url”:url
    
},
    
url“getpage.php”,
    
success: function (data) {
    $(
“#result”).empty();
    if (
data.indexOf(ERROR_COMMENT) >= 0) {
      
// エラー時の処理
      
$(“#result”).text(“Failed…”);
    } else {
      
// 通常時の処理
      
$(“#result”).text(“Load!”);
    }
      $(
“#result”).append(data);
    }
  });
}
//–>
</script>

</head>
<body>
<form id=”search”>
  <input type=”text” id=”url” />
  <input type=”submit” value=”チェック” />
</form>

<div id=”result”></div>

</body>
</html>

getpage.php


<?php

# エラー時に出力するメッセージ
# Java Script の方と同じエラーメッセージにしてください。
$ERROR_COMMENT = “ReadingFileErrorOccurred”;

# 全てのエラーを errorHandler で処理するように設定します。
error_reporting(0);
function
errorHandler ($errno, $errstr, $errfile, $errline){
    global
$ERROR_COMMENT;
        echo
$ERROR_COMMENT.“ : ”.$errstr;
}
set_error_handler(“errorHandler”);

# Ajax から渡された URL データを読み込みます。
if ($_GET{‘url’}) {
  
$url = urldecode($_GET{‘url’});
} else {
  
$url = urldecode($_POST{‘url’});
}

if( is_url($url) ) {
    
# Ajax での データ入出力の文字コードは UTF-8 なので UTF-8に変換
    # 読み込む最大ファイルサイズを指定しない場合は
    # file_get_contents($url, FALSE, NULL)
    # としてください。
    
echo mb_convert_encoding(
    
file_get_contents($url, FALSE, NULL, 0, 10000),
    
“UTF-8″,
    
“auto”);
} else {
    
trigger_error(“URLが不正です。”, E_USER_WARNING);
}

# $text がURLとして正しい形式かどうかをチェック
#
function is_url($text) {
    if (
preg_match(‘/^(https?|ftp)(://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)$/’, $text)) {
        
return TRUE;
    } else {
        return
FALSE;
    }
}

?>

なお、ソース内にも書いていますが、Ajax ではデータ入出力の文字コードはは UTF-8 です。

そのため、anotherDomain.html も getpage.php も UTF-8 形式で保存してください。

使用上の注意として getpage.php は外部からアクセスできないようにパーミッションを設定のこと。

カテゴリー: JavaScript, 日記   パーマリンク

jQueryで別ドメインのページを読み込む への16件のコメント

  1. 匿名 より:

    このソースコピペでつかえないんですね。。

  2. ピンバック: URL入力でソースコード取得|ajax | サイト制作の調べ

  3. You should take part in a contest for one of the greatest websites on the net.
    I will highly recommend this blog!

    my blog Slitherio big snake

  4. Players on the sideline conferred with coaches and teammates seeking a way to increase
    their performance. Whatever your starting point is, start with one and collect them as you go.
    Every youth football team needs to be taught correct fundamentals and that
    isn’t often the case.

  5. I believe that is one of the such a lot vital info for me.
    And i am happy studying your article. However wanna commentary on some general things,
    The Dynamic Web Design site style is wonderful, the articles is really nice :
    D. Good job, cheers

  6. Hassie より:

    Having read this I thought it was rather informative. I appreiate you spending some time
    and energy Shatter to Vape Juice (Hassie) put
    this informative article together. I once again find myself personally spending a lot of time both reading and leaving
    comments. But so what, it was still worth it!

  7. I’ve also thought about seeing a But I’ll definitely start of by trying some different Thanks for the help

  8. Maybe he made it just for You’re now the asshole brother for hating his handmade, thing?

  9. Dale より:

    Howdy I am so glad I found ypur blog, I really found you by mistake, while I was researching on Bing for
    something else, Anyways I am here now and would just like to say thanks a
    lot for a tremendous post and a all round entertaining blog (I also love the theme/design), I don’t have timee
    to browse it all at the minute but I have saved it and also added your RSS feeds, so when I
    have time I will be back to read a lot more, Please do keep up the great
    work.

  10. Thanks for your personal marvelous posting! I
    genuinely enjoyed reading it, you happen to be a great author.I will
    be sure to bookmark your blog and will eventually come back
    later on. I want to encourage you tto continue your great
    job, have a nice morning!

  11. Lip Balm Boxes より:

    Why people still use to read news papers when in this technological world the whole thing is available on web?

  12. Corey より:

    Excellent blog! Do you have anny tips andd hints for aspiring writers?
    I’m planning to start myy econ review, Corey, own blog soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or go for a paid
    option? There are so many options out there that I’m totally overwhelmed ..
    Any tips? Appreciate it!

  13. official site より:

    Right here is the perfect webpage for anyone who wants to understand tthis topic.
    You know so much its alpmost hard to argue with yyou (not thast I actually would want to…HaHa).
    You definitely put a brwnd new spin oon a subject that’s been written about for a long time.
    Excellent stuff, just great!

  14. Wypożyczalnia samochodów w Gdańsku oferuje tani wynajem aut osobowych i dostawczych na terenie Trójmiasta i okolic. budynekfirmy zlokalizowana jest tuż przy dworcu kolejowym, będącym doskonałym węzłem komunikacyjnym z Gdynią i Sopotem. Niewielka dystans dzieląca tanią wypożyczalnię samochodów od lotniska im. Lecha Wałęsy upoważnia na przejazd w czasie krótszym niż 30 minut.

  15. Bursasbobet より:

    Attractive section of content. I just stumbled upon your website and in accession capital to assert that I get in fact enjoyed
    account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement you access consistently
    fast.

http://www.umbrellababyshowerinvitations.com/rooftop-weddings-are-simply-wow/ への返信 コメントをキャンセル

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>