JS:Ajax:動的に別ドメインのスクリプト呼び出し
JavaScript・XHTML・CSS (43 items)
2005年11月28日
>Ajaxでランダムなリンクの切替
上記でも触れましたが、
”XMLHttpRequest”なんかを使ってスクリプトを呼び出す場合、
そのスクリプトは同じドメインのものでないといけません。
上記サンプルのhtmlやJavaScript(PHP)は、
「www.res-system.com」ドメインの中にいないといけないという事です。
しかし、scriptタグからスクリプトを呼び出す場合、
別ドメイン(外部サイト)のスクリプトを参照したい場合もあります。
で、上記サンプルと同じ動きで、
スクリプトが別ドメインにあるサンプルを作ってみました。
まずは下記のリンクから動作をご覧ください。。
>Ajax Sample2
htmlが「www.web-artisan.jp」ドメインで、そこから、
「www.res-system.com」ドメインのJavaScript(PHP)を呼んでいます。
以下、ソース。
・http://www.web-artisan.jp/skins/ajax/ajax2.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Ajax Sample2</title>
</head>
<body>
<script type="text/javascript">
<!--
function call_js()
{
var ajax2 = document.getElementById('ajax2');
var out = document.createElement('script');
out.src='http://www.res-system.com/weblog/media/1/ajax2.php';
ajax2.appendChild(out)
}
//3秒置きに読みこみ
timerID = setInterval("call_js()", 3000);
//-->
</script>
<p>3秒おきにリンクを読みこみ直します</p>
<div id="ajax2">
</div>
</body>
</html>
ajax2.htmlでは、
「www.res-system.com」ドメインのajax2.phpを呼び出す為の
scriptタグを生成しています。
ここでのポイント、今回のテーマでも大事なんですが、
scriptタグの生成には、下記記事のようにDOMを使用しています。
>JS:DOMを使ったJavaScriptによる文字の書きこみ
ここで、”document.write”や”innerHTML”を使用してscriptタグを生成しても、
scriptは呼び出されないようです。
・http://www.res-system.com/weblog/media/1/ajax2.php
<?php
header("Content-type: application/x-javascript");
$url[1] = 'http://www.res-system.com/weblog/';
$url[2] = 'http://www.yahoo.co.jp/';
$url[3] = 'http://www.msn.co.jp/';
$url[4] = 'http://www.goo.ne.jp/';
$url[5] = 'http://www.google.co.jp/';
$title[1] = 'Web Artisan Blog';
$title[2] = 'Yahoo!';
$title[3] = 'MSN';
$title[4] = 'goo';
$title[5] = 'Google';
//ランダムに取得
$i = mt_rand(1, 5);
print <<<END
var ajax2 = document.getElementById('ajax2');
var text = document.createTextNode('$title[$i]');
var p = document.createElement('p');
var a = document.createElement('a');
var href = a.setAttribute('href', '$url[$i]');
var old = ajax2.firstChild;
a.appendChild(text);
p.appendChild(a);
ajax2.replaceChild(p, old);
END;
?>
ajax2.phpからhtmlを出力しますが、ここでもDOMを使用します。
細かい処理説明は省きますが、DOMでは、
replaceChildなんかで、一度生成したタグの置き換えもできるんです。
このサンプルからも言えますが、
Ajaxという括りで色々したい場合、
やはりDOMというものを使用すれば、柔軟に対応できそうです。
この記事に関連した過去記事一覧は画面下にあります。
Comments
Elan Hung wrote:
There's a terrible leak in your code. Ev ery 3 seconds a new <script> tag is inserted to your document and you never manage to clean up old ones. Who's knows whats gonna happen when the memory stack explodes?2006年05月26日 23時12分30秒
ossi wrote:
確かに、上記コードはメモリリークが発生します。オブジェクト解放してませんし。。よって、参考程度にしてくださいね。このまま実用しないでください。。。
2006年05月31日 15時38分01秒
Add Comments
Trackback
トラックバックはありません
Trackback URL
http://www.res-system.com/weblog/action.php?action=plugin&name=TrackBack&tb_id=536