jQury + Ajax : load()

jQuery 裡頭寫 Ajax 比原始的寫法簡單些。我十分需要有從外部載入文件(xml 檔案、html 文件,或是 cgi 程式傳回來的資料)的功能,
load(url, params, callback)
這個功能可以將遠端的 HTML 檔案插入成為目前網頁的一個 DOM 物件。

底下的範例是一個簡單 html 網頁,同樣的,利用 $(fn)。而它所描述的情景就是說:
當 id 為 generate 的元素被點選之後($("#generate").click(fn)),就開始載入不同來源的遠端文件,並且塞入不同 id 的區塊。
$("#phpecho").load("http://localhost/withjs/script.php");
$("#loadxml").load("http://localhost/bibleTest/genesis.xml");
$("#loadhtml").load("http://localhost/happy.html");

這三行都一樣,翻譯成人可以懂的話:jquery 找到 id 為 phpecho、loadxml、loadhtml 三個區塊,然後載入指定網址的內容。

需要提醒的是,Ajax 不允許跨 domain 存取資料,因此,若是您要的遠端在別人家裏,那就要寫 proxy。

<html>
....
<head>
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript">
<!--
 
$(function(){
	$("#generate").click(function(){
		$("#phpecho").load("http://localhost/withjs/script.php");
		$("#loadxml").load("http://localhost/bibleTest/genesis.xml");
		$("#loadhtml").load("http://localhost/happy.html");

	});
});

//-->
</script>

</head>
<body>
<div id="wrapper">
   <div id="quote"><p></p></div>
   <div id="phpecho"></div>
   <div id="loadxml"></div>
   <div id="loadhtml"></div>
   <input type="submit" id="generate" value="Generate!">
 </div> 

</body>
</html>

0 comments on jQury + Ajax : load()

    Post new comment

    The content of this field is kept private and will not be shown publicly.
    • Web page addresses and e-mail addresses turn into links automatically.
    • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img><blockquote>
    • Lines and paragraphs break automatically.

    More information about formatting options

    CAPTCHA
    This question is for testing whether you are a human visitor and to prevent automated spam submissions.