ajax 获取另外一个html页面并通过获取其中的部分来插入当前html方式有两种
1,通过<code></code>来包装获取
$.ajax({
url:url,
type:"GET",
dataType:"html",
success:function(result){
console.log(result);
var Obj = $("<code></code>").append($(result));//包装数据
//(需要获取的对应块(如class='aa')
var $html = $(".aa", Obj);
console.log($html.html());
//获取对应块中的内容
var value = $html.html();
//获得内容可以用append插入对应的div中,也可以用html(value)直接添加
}
});
2,通过正则表达式来实现
$.ajax({
url:url,
type:"GET",
dataType:"html",
success:function(result){
console.log(result);
//正则表达式获取body块
var reg = /[\s\S]*<\/body>/g;
var html = reg.exec(result)[0];
//然后用filter来筛选对应块对象,如:class='aa'
var aa = $(html).filter(".aa");
var aahtml = aa.html();
console.log(aahtml);
//获取内容后可以插入当前html中。。。
}
});
以上两种方式亲测过可用
3,可以通过jquery load()方法中添加标签来获取其中部分加载
//a1为当前页加载的DIV块,.b为加载html中class=b的块
$(".a1").load("userInfo.html .b");
以上是转载内容,出处:https://blog.csdn.net/wzhen3103/article/details/77921885
以下为示例↓: demo.html 文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="infohtml">
<div><h2>标题</h2></div>
<div style="font-size: 50px;">内容内容内容内容内容内容内容内容内容</div>
<div class="footer" style="font-size: 25px;">底部信息</div>
</div>
</body>
</html>
test.html 文件,浏览器访问该文件即可
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function AjaxLoadContentFun() {
$.ajax({
type:"get",
url:"demo.html",
dataType:"html",
data:{},
}).done(function (data) {
// alert(data);return false;
var HtmlObj = $("<code></code>").append($(data));//包装数据
//(需要获取的对应块或页面文件的id,如:(id='infohtml')
var HtmlFind = $("#infohtml", HtmlObj);
// console.log(HtmlFind.html());
//获取对应块中的内容
var GetHtml = HtmlFind.html();
//获得内容可以用append插入对应的div中,也可以用html(GetHtml)直接添加
// $('#contentids').html(GetHtml);
$('#contentids').append(GetHtml);
}).fail(function () {
alert('Error');
})/*.always(function () {
alert('未知');
})*/;
}
$(function () {
AjaxLoadContentFun();
});
</script>
</head>
<body>
<button onclick="AjaxLoadContentFun();">按钮</button>
<div style="width: 100%;height: 50px;font-weight: bold;background: #ffd3a2;">测试</div>
<div id="contentids"></div>
<div style="width: 100%;height: 100px;background: #ff8e1b;">测试</div>
</body>
</html>