.load()
.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] ) 返回: jQuery
描述: 載入遠(yuǎn)程 HTML 文件代碼并插入至 DOM 中。
-
version added: 1.0.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] )
url一個(gè)包含發(fā)送請(qǐng)求的URL字符串
data向服務(wù)器發(fā)送請(qǐng)求的Key/value參數(shù),例如{name:"愚人碼頭",age:23}
complete(responseText, textStatus, XMLHttpRequest)當(dāng)請(qǐng)求成功后執(zhí)行的回調(diào)函數(shù)。
這個(gè)方法是從服務(wù)器獲取數(shù)據(jù)最簡單的方法。除了是一個(gè)不是全局函數(shù),這個(gè)方法和$.get(url, data, success) 基本相同,它有一種隱含的回調(diào)函數(shù)。 當(dāng)他檢查到一個(gè)成功的請(qǐng)求(i.e. 當(dāng) textStatus是 "success" 或者 "notmodified"),.load() 方法將返回的HTML 內(nèi)容數(shù)據(jù)設(shè)置到相匹配的節(jié)點(diǎn)中。這就意味著大多數(shù)采用這個(gè)方法可以很簡單:
$('#result').load('ajax/test.html');
如果提供回調(diào),都將在執(zhí)行后進(jìn)行后處理:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
在上文的兩個(gè)例子中, 如果當(dāng)前的文件不包含ID為“result”的元素,那么.load()方法將不被執(zhí)行。
默認(rèn)使用 GET 方式 - 傳遞附加參數(shù)時(shí)自動(dòng)轉(zhuǎn)換為 POST 方式。
注意: 事件處理函數(shù)中也有一個(gè)方法叫
.load()。 哪一個(gè)被使用取決于傳遞的參數(shù)設(shè)置。
加載頁面片段
.load() 方法, 不像 $.get(),允許我們指定遠(yuǎn)程文件被插入的部分。 他是一個(gè)特殊的 url 參數(shù)。 一個(gè)或多個(gè)空格字符被包括在這個(gè) url 參數(shù)字符串中, 在這個(gè)字符串被第一空格劃分jQuery選擇內(nèi)容將被載入。
我們可以修改上述例子中,只有“#container”部分被載人到文件中:
$('#result').load('ajax/test.html #container');
當(dāng)這種方法執(zhí)行, 它將檢索 ajax/test.html 頁面的內(nèi)容,jQuery會(huì)獲取ID為 container 元素的內(nèi)容,并且插入到ID為 result 元素,而其他的被檢索到的元素將被廢棄。
舉例:
例子: Load the main page's footer navigation into an ordered list.
<!DOCTYPE html>
<html>
<head>
<style>
body{ font-size: 12px; font-family: Arial; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<b>Footer navigation:</b>
<ol id="new-nav"></ol>
<script>
$("#new-nav").load("/ #jq-footerNavigation li");
</script>
</body>
</html>
Demo:
例子: 顯示一個(gè)信息如果Ajax請(qǐng)求遭遇一個(gè)錯(cuò)誤
<!DOCTYPE html>
<html>
<head>
<style>
body{ font-size: 12px; font-family: Arial; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
</body>
</html>
Demo:
例子: 將feeds.html 文件載人到 ID為feeds的DIV.
$("#feeds").load("feeds.html");
結(jié)果:
<div id="feeds"><b>45</b> feeds found.</div>
例子: 發(fā)送數(shù)組形式的data參數(shù)到服務(wù)器。
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
例子: 同上, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});