1. 程式人生 > >jQuery load() 方法實現載入遠端資料

jQuery load() 方法實現載入遠端資料

jQuery load() 方法是簡單但強大的 AJAX 方法。load() 方法從伺服器載入資料,並把返回的資料放入被選元素中。

語法:
$(selector).load(URL,data,callback);必需的 URL 引數規定您希望載入的 URL。可選的 data 引數規定與請求一同傳送的查詢字串鍵/值對集合。可選的 callback 引數是 load() 方法完成後所執行的函式名稱。

這是示例檔案("demo_test.txt")的內容:

<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
下面的這句話會把檔案 "demo_test.txt" 的內容載入到指定的 <div> 元素中:

$("#div1").load("demo_test.txt");

也可以把 jQuery 選擇器新增到 URL 引數。

下面的例子把 "demo_test.txt" 檔案中 id="p1" 的元素的內容,載入到指定的 <div> 元素中:

$("#div1").load("demo_test.txt #p1");

可選的 callback 引數規定當 load() 方法完成後所要允許的回撥函式。回撥函式可以設定不同的引數:

•responseTxt - 包含呼叫成功時的結果內容
•statusTXT - 包含呼叫的狀態
•xhr - 包含 XMLHttpRequest 物件
下面的例子會在 load() 方法完成後顯示一個提示框。如果 load() 方法已成功,則顯示“外部內容載入成功!”,而如果失敗,則顯示錯誤訊息:

完整的例子

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("/example/jquery/demo_test.txt",function(responseTxt,statusTxt,xhr){
      if(statusTxt=="success")
        alert("外部內容載入成功!");
      if(statusTxt=="error")
        alert("Error: "+xhr.status+": "+xhr.statusText);
    });
  });
});
</script>

</head>
<body>

<div id="div1"><h2>使用 jQuery AJAX 來改變文字</h2></div>
<button>獲得外部內容</button>

</body>
</htm