jQuery load() 方法是简单但强大的 AJAX 方法。load() 方法从服务器加载数据,并把返回的数据放入被选元素中。html
语法:
$(selector).load(URL,data,callback);必需的 URL 参数规定您但愿加载的 URL。可选的 data 参数规定与请求一同发送的查询字符串键/值对集合。可选的 callback 参数是 load() 方法完成后所执行的函数名称。jquery
这是示例文件("demo_test.txt")的内容:ajax
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
下面的这句话会把文件 "demo_test.txt" 的内容加载到指定的 <div> 元素中:api
$("#div1").load("demo_test.txt");服务器
也能够把 jQuery 选择器添加到 URL 参数。函数
下面的例子把 "demo_test.txt" 文件中 id="p1" 的元素的内容,加载到指定的 <div> 元素中:google
$("#div1").load("demo_test.txt #p1");spa
可选的 callback 参数规定当 load() 方法完成后所要容许的回调函数。回调函数能够设置不一样的参数:htm
•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></html>