jQuery 的 .load()
方法是一个 AJAX 方法,用于从服务器加载数据并将返回的 HTML 放入匹配的元素中。当需要加载具有特定 ID 的元素时,可以通过 URL 片段标识符来实现。
$(selector).load(url, [data], [complete]);
要从远程页面加载特定ID的元素及其内容:
$('#result').load('ajax/test.html #container');
这个例子会从 test.html
文件中加载 ID 为 container
的元素,并将其内容插入到当前页面中 ID 为 result
的元素中。
原因:
解决方案:
$('#result').load('ajax/test.html #container', function(response, status, xhr) {
if (status == "error") {
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});
原因:.load()
方法会剥离脚本标签
解决方案:
$.get('ajax/test.html', function(data) {
$('#result').html($(data).find('#container'));
// 手动执行脚本
$('#result').find('script').each(function() {
$.globalEval(this.text || this.textContent || this.innerHTML || '');
});
});
解决方案:添加时间戳参数
$('#result').load('ajax/test.html #container?' + new Date().getTime());
<!DOCTYPE html>
<html>
<head>
<title>jQuery Load Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="result">Loading content...</div>
<button id="loadBtn">Load Content</button>
<script>
$(document).ready(function() {
$('#loadBtn').click(function() {
$('#result').load('external.html #specific-content', function(response, status, xhr) {
if (status == "error") {
$('#result').html("Sorry, there was an error loading the content.");
}
});
});
});
</script>
</body>
</html>
通过合理使用 jQuery 的 .load()
方法,可以高效地实现页面内容的动态更新和加载。