## jQuery load() 方法
jQuery[load() 方法](https://www.w3cschool.cn/jquery/event-load.html)是簡單但強大的 AJAX 方法。
load() 方法從服務器加載數據,并把返回的數據放入被選元素中。
**語法:**
```
$(*selector*).load(*URL,data,callback*);
```
必需的*URL*參數規定您希望加載的 URL。
可選的*data*參數規定與請求一同發送的查詢字符串鍵/值對集合。
可選的*callback*參數是 load() 方法完成后所執行的函數名稱。
這是示例文件("demo\_test.txt")的內容:
```
jQuery and AJAX is FUN!!!
This is some text in a paragraph.
```
下面的例子會把文件 "demo\_test.txt" 的內容加載到指定的 元素中:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("/statics/demosource/demo_test.txt");
});
});
</script>
</head>
<body>
<div id="div1"><h2>使用 jQuery AJAX</h2></div>
<button>獲取外部內容</button>
</body>
</html>
```
也可以把 jQuery 選擇器添加到 URL 參數。
下面的例子把 "demo\_test.txt" 文件中 id="p1" 的元素的內容,加載到指定的 元素中:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("/statics/demosource/demo_test.txt #p1");
});
});
</script>
</head>
<body>
<div id="div1"><h2>使用 jQuery AJAX 修改文本</h2></div>
<button>獲取外部文本</button>
</body>
</html>
```
可選的 callback 參數規定當 load() 方法完成后所要允許的回調函數。回調函數可以設置不同的參數:
* *responseTxt*\- 包含調用成功時的結果內容
* *statusTXT*\- 包含調用的狀態
* *xhr*\- 包含[XMLHttpRequest 對象](https://www.w3cschool.cn/xml/xml-http.html)
下面的例子會在 load() 方法完成后顯示一個提示框。如果 load() 方法已成功,則顯示"外部內容加載成功!",而如果失敗,則顯示錯誤消息:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("/statics/demosource/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>
</html>
```
**提示:**在jQuery的load()方法中,無論AJAX請求是否成功,一旦請求完成(complete)后,回調函數(callback)立即被觸發。
- 簡介
- 安裝
- 語法
- 選擇器
- 事件
- click
- dblclick
- mouseenter
- mouseleave
- mousedown
- mouseup
- hover
- focus
- blur
- 鍵盤事件
- 效果
- 隱藏和顯示
- 淡入淡出
- 滑動
- 動畫
- 停止滑動
- jQuery Callback 方法
- jQuery Chaining
- jQuery_HTML
- jQuery獲取
- jQuery設置
- jQuery添加元素
- jQuery刪除元素
- jQuery CSS類
- jQuery css() 方法
- jQuery 遍歷
- jQuery AJAX
- jQuery AJAX簡介
- jQuery - AJAX load() 方法
- jQuery - AJAX get() 和 post() 方法